Using safe $apply
In the course of developing AngularJS applications, you will become very familiar with $apply()
and its implications. The $apply()
function cannot be invoked while the $apply()
phase is already in progress without causing AngularJS to raise an exception. While in simpler applications, this problem can be solved by being careful and methodical about where you invoke $apply()
; however, this becomes increasingly more difficult when applications incorporate third-party extensions with high DOM event density. The resulting problem is one where the necessity of invoking $apply
is indeterminate.
As it is entirely possible to ascertain the state of the application when $apply()
might need to be invoked, you can create a wrapper for $apply()
to ascertain the state of the application, and conditionally invoke $apply()
only when not in the $apply
phase, essentially creating an idempotent $apply()
method.
Tip
This recipe contains content that the AngularJS wiki considers an anti-pattern...