Can I prevent / delay the AngularJS $digest from h

2019-01-27 13:17发布

问题:

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

回答1:

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.