How can I get a controller to update in Angularjs?

I use the Ionic Framework for the application and adhere to one thing. In my application, I have a Favorites view, which displays a list of items that the user used elsewhere in the application. The problem is that the code in the controller runs only on the first hit of the Favorites route. If the user adds a favorite place in another place to the application, then returns to the "Favorites" mode, the list is not restored.

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 executes a 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 favorites controller to be updated after the user has added a new favorite to the database? I tried to add the region reload function to the controller, and also add reload: true for $ stateProvider for the route, but it didn't make any difference.

+5
source share
2 answers

Use broadcasting anywhere and grab it everywhere:

Anywhere in the application:

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

On the appropriate 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 thing if you want to expand your level

+10
source

you can use ui-router and enable / reload () to reload the controller / view:

  .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 }); }] }) 
+1
source

Source: https://habr.com/ru/post/1209092/


All Articles