Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I prevent / delay the AngularJS $digest from happening when model is updated

Is there a way to postpone or delay a digest from happening?

I have a bunch of changes that I want to make to a model but I don't want the digest to fire until all changes to the model were made. Some of the objects on the model have watchers that update other objects on the model to change.

Ideally I'd like to

  • Stop the $digest
  • Make all changes to the model
  • Start the $digest

The $digest will find all dirty objects and fire the watchers.

Another solution to this is to, instead of stopping $digest I could

  • Remove the watchers
  • Make all changes to the model (digest still runs)
  • Add the watchers that were removed

After the watchers are added I'd need to run the watcher methods to ensure that the model is in the correct state.

I just feel the 2nd option seems like its a hack.

Ideas??

like image 616
Brad8118 Avatar asked Jan 15 '14 15:01

Brad8118


People also ask

How do you fix $Digest already in progress?

There are a few ways to deal with this. The easiest way to deal with this is to use the built in $timeout, and a second way is if you are using underscore or lodash (and you should be), call the following: $timeout(function(){ //any code in here will automatically have an apply run afterwards });

What triggers digest cycle in AngularJS?

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 $Digest in AngularJS?

The $digest() function is called whenever AngularJS thinks it is necessary. For instance, after a button click handler has been executed, or after an AJAX call returns (after the done() / fail() callback function has been executed).

How do you use $Digest in AngularJS?

The $digest cycle starts as a result of a call to $scope. $digest() . Assume that you change a scope model in a handler function through the ng-click directive. In that case AngularJS automatically triggers a $digest cycle by calling $digest() .


1 Answers

This is not a hack at all. Its a good question because large data sets can cause the $digest cycle to run very slowly when a user inputs text rapidly or holds down backspace. You can definitely do performance tweaks like being careful with your $watch and $filter functions, but sometimes its a better idea to delay the $digest cycle using a debounce function.

like image 173
Aaron Gray Avatar answered Oct 07 '22 09:10

Aaron Gray