how to call function when angular watch cycle or digest cycle is completed

Shivek Parmar picture Shivek Parmar · Mar 17, 2015 · Viewed 23.9k times · Source

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

Answer

guru picture guru · Mar 17, 2015

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.