Reputation: 55729
At some point after a user action I would like to cause a digest to occur, so the UI reflects a change in the data-model backing it.
I have a service that performs some change in a callback (asynchronously).
I understand that $scope
only makes sense in the context of a controller. Can I achieve the same effect by performing $apply()
on the $rootScope
?
I have seen code that checks for $$phase
or similar related to avoiding digest errors, what checks should I perform in order to trigger a digest safely?
Upvotes: 5
Views: 7104
Reputation: 53600
See this answer: Running $apply on $rootScope vs any other scope
You can call $rootScope.$apply()
outside of a controller (i.e. in a service) in order to trigger a digest loop.
Alternatively, you could consider using $broadcast
and $on
to send a notification to other parts of your app when something needs refreshing. (See Understanding Angular’s $scope and $rootScope event system $emit, $broadcast and $on)
// in a service
$rootScope.$broadcast('myCustomEvent', {
someProp: 'foobar'
// other data
});
// in a controller or another service
$scope.$on('myCustomEvent', function (event, data) {
console.log(data);
// do something with this event
});
Upvotes: 8