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

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)