How can I get a controller to refresh in Angularjs

2019-04-09 00:03发布

问题:

I'm using Ionic Framework for an app and am sticking on one part. In my app I have a Favourites view, which displays a list of items that a user has favourited elsewhere in the app. The problem is, the code in the controller is only run once the first time the Favourites route is hit. If a user then adds a favourite somewhere else in the app, then goes back to the Favourites view, the list isn't regenerated.

In my controller, I have the following:

Favourites.all().then(function(results){
    angular.forEach(results, function(value, key){
        // add results to an array to present in the view
    })
})

I have a Factory that does the database query:

.factory('Favourites', function(DB){
    var self=this;
    console.log("test 1");

    self.all = function() {
        return DB.query('SELECT * FROM favourites')
            .then(function(result){
                return DB.fetchAll(result);
            });
    };
    return self;
})

My question is, how can I get the Favourites controller to refresh after a user has added a new favourite to the database? I tried adding a scope reload function to the controller, and also adding reload:true to the $stateProvider for the route, but neither made any difference.

回答1:

Use broadcasting from anywhere and catch it wherever:

Anywhere in your app:

$scope.onNewFavoriteHandler = function() {
    //Add to DB logic
    $rootScope.$broadcast('new-favorite');
}

On the relevant controller:

$scope.$on('new-favorite', function(event, args) { 
    Favourites.all().then(function(results){
        angular.forEach(results, function(value, key){
            // add results to an array to present in the view
        })
    });
    // do what you want to do
})

Nice artice if you wish to extend your knoledge



回答2:

you can use ui-router and resolve/reload() to get your controller/view to reload:

  .state('somestate', {
    url: '/somestate',
    templateUrl: '/path/to/some/view.html',
    resolve: {
      favorites: ['Favourites', function ($Favourites) {
        return Favourites.all();
      }]
    },
    controller: ['$scope', '$state', 'favorites', function ($scope, $state, favorites) {
      angular.forEach(favorites, function(value, key){...});

      //...later...
      $scope.onSomethingHappened = function reload(){
            var current = $state.current;
            var params = angular.copy($stateParams);
            $state.transitionTo(current, params, { reload: true, inherit: true, notify: true });          
    }]
  })