Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular / Ionic - controller only runs once

I'm starting out with Angular through the Ionic Framework but I am failing to understand why the controller only runs once i.e. I change state, the controller runs, change to another state and then back again and the controller does not run a second time. This is my state:

$stateProvider.state( 'container.previous', {
    url: 'previous',
    views: {
        main : {
            templateUrl : 'views/previous.html',
            controller : function( $scope, $cordovaSQLite ){
                $scope.firms = [];
                $cordovaSQLite.execute(window.db, "SELECT * FROM recent GROUP BY phone ORDER by id DESC").then(function(res) {
                    for (i = 0; i < res.rows.length; i++) {
                        $scope.firms.push(res.rows.item(i));
                    }
                }, function (err) {
                    console.error(err);
                });
            }
        }
    },
    onStateChangeStart : function(){
        backButton = true;

    }
});

In another state, if you click on a button related to a "firm", it saves the "firms" data to local storage. The above state shows the firms in which you have previously clicked on. But I cannot figure out how to update the $scope.firms correctly as the controller never runs again.

Can anyone help me out?

like image 484
Luke Snowden Avatar asked Mar 26 '15 08:03

Luke Snowden


1 Answers

You can put the code you want to run in $ionicView.enter:

controller : function( $scope, $cordovaSQLite ){
    $scope.$on('$ionicView.enter', function() {
        // code to run each time view is entered
    });

    ...
});

See "View LifeCycle and Events": https://ionicframework.com/docs/v1/api/directive/ionView/

like image 189
brandyscarney Avatar answered Sep 19 '22 17:09

brandyscarney