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

1

19

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??

Standpoint answered 15/1, 2014 at 15:32 Comment(3)
"The $digest will find all dirty objects and fire the watchers." - the solution is to set up your $watches to handle the changes appropriately if (newVal ...) { // do something. If your architecture is good, you would never want to stop the $digest. It's your friend!Millymilman
I think this is a valid question. I have instances where I change the value of a $scope variable and it does not display the updated version. If I say $scope.$apply() it complains that a digest is already in progress.Mccray
Sample code to stop and clear watchers is shown here:- #38382308Upmost
W
13

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.

Whippletree answered 18/9, 2014 at 2:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.