0

I want to execute some function on every $digest cycle.

The documentation for $scope reads:

If you want to be notified whenever $digest is called, you can register a watchExpression function with no listener. (Since watchExpression can execute multiple times per $digest cycle when a change is detected, be prepared for multiple calls to your listener.)

So does that mean it can be accomplished this way:

$rootScope.$watch(function () {
  // Cron job
});

I'm not sure if every $digest cycle hits the $rootScope, or is it even emitted from $rootScope. I only know there's only 1 $digest loop and it occurs every time a $watch detects changes.

pilau
  • 6,635
  • 4
  • 56
  • 69
  • 1
    Check my answer here: http://stackoverflow.com/questions/21138388/angular-js-identify-an-digest-complete-event-and-removing-from-url-in-angular/21138524#21138524 – Ilan Frumer Jan 22 '14 at 15:58
  • @IlanFrumer saw it, and one-upped you as well! – pilau Jan 22 '14 at 20:10

1 Answers1

2

Q: So does that mean it can be accomplished this way?

A: Yes, although some directives/services might choose to only digest their local scope to improve performance.

That said it's recommended to execute as less code as possible in a digest loop.

digest isn't like a cron job, it doesn't run automatically every x seconds.
It runs when you call $scope.$apply() or when an event like ng-click or $http.get occurs.

Bob Fanger
  • 28,949
  • 7
  • 62
  • 78
  • Thanks for the prompt answer. You got me curious as well - what is the difference between digesting a local scope and the opposite? – pilau Jan 22 '14 at 19:40
  • You call $scope.$digest when you're sure that only that $scope or its childscopes have changed. This limits the dirty-checking compared to $scope.$apply which dirty-checks all $scopes and additionally $eval()s the argument. – Bob Fanger Jan 28 '14 at 12:50