Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing a digest in Angular

Tags:

angularjs

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?

like image 680
Ben Aston Avatar asked Feb 02 '15 22:02

Ben Aston


People also ask

Which function is used to trigger the digest cycle process manually?

To answer your question, scope. $parent. $digest() will trigger a digest on scope 's parent.

What is digest cycle in angular?

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.

What is the difference between Digest () and apply ()?

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.

What is scope Digest ()?

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.


1 Answers

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
});
like image 108
Nate Barbettini Avatar answered Oct 02 '22 10:10

Nate Barbettini