Is there any way to call custom function in angular after angular finishes all watch cycle.
Requirement I have multiple watch functions inside my controller. Now I want to execute a function only after all watch functions are executed by angular
For example, if you use JavaScript's setTimeout() function to update a scope model, Angular has no way of knowing what you might change. In this case it's your responsibility to call $apply() manually, which triggers a $digest cycle.
$digest() gets called without any arguments. $apply() takes a function that it will execute before doing any updates. The other difference is what they affect. $digest() will update the current scope and any child scopes.
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 angular JS watch function? The angular JS $watch function is used to watch the scope object. The $watch keep an eye on the variable and as the value of the variable changes the angular JS $what runs a function. This function takes two arguments one is the new value and another parameter is the old value.
There are couple of ways to do register a callback once a digest is completed.
Using $$postDigest
:
$scope.$$postDigest
fires a callback after the current $digest
cycle completed.
However this runs only once after the next digest cycle. To make it run after each digest cycle run it along with $watch
. This is based on the code sample given here
var hasRegistered = false;
$scope.$watch(function() {
if (hasRegistered) return;
hasRegistered = true;
$scope.$$postDigest(function() {
hasRegistered = false;
fn();
});
});
The $watch
can get triggered multiple times during a digest cycle so we use a flag hasRegistered
to prevent $$postDigest
callback to be registered multiple times.
Note: $$postDigest will not trigger another digest cycle. So any modifcation to $scope
inside $$postDigest
will not get reflected in the dom. $$
means this is a private function in angularjs, so the function is not stable and may change in the future.
Using $timeout
:
$timeout(function(){
console.log("Running after the digest cycle");
},0,false);
This runs after the current digest cycle is complete. Note: The third argument is set to false to prevent another digest cycle trigger.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With