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?
To answer your question, scope. $parent. $digest() will trigger a digest on scope 's parent.
Digest cycle is what Angular JS triggers when a value in the model or view is changed. The cycle sets off the watchers which then match the value of model and view to the newest value. Digest cycle automatically runs when the code encounters a directive.
One difference between the two is how they are called. $digest() gets called without any arguments. $apply() takes a function that it will execute before doing any updates.
At key points in your application AngularJS calls the $scope. $digest() function. This function iterates through all watches and checks if any of the watched variables have changed. If a watched variable has changed, a corresponding listener function is called.
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With