AngularJS : Prevent error $digest already in progress when calling $scope.$apply() AngularJS : Prevent error $digest already in progress when calling $scope.$apply() angularjs angularjs

AngularJS : Prevent error $digest already in progress when calling $scope.$apply()


From a recent discussion with the Angular guys on this very topic: For future-proofing reasons, you should not use $$phase

When pressed for the "right" way to do it, the answer is currently

$timeout(function() {  // anything you want can go here and will safely be run on the next digest.})

I recently ran into this when writing angular services to wrap the facebook, google, and twitter APIs which, to varying degrees, have callbacks handed in.

Here's an example from within a service. (For the sake of brevity, the rest of the service -- that set up variables, injected $timeout etc. -- has been left off.)

window.gapi.client.load('oauth2', 'v2', function() {    var request = window.gapi.client.oauth2.userinfo.get();    request.execute(function(response) {        // This happens outside of angular land, so wrap it in a timeout         // with an implied apply and blammo, we're in action.        $timeout(function() {            if(typeof(response['error']) !== 'undefined'){                // If the google api sent us an error, reject the promise.                deferred.reject(response);            }else{                // Resolve the promise with the whole response if ok.                deferred.resolve(response);            }        });    });});

Note that the delay argument for $timeout is optional and will default to 0 if left unset ($timeout calls $browser.defer which defaults to 0 if delay isn't set)

A little non-intuitive, but that's the answer from the guys writing Angular, so it's good enough for me!


Don't use this pattern - This will end up causing more errors than it solves. Even though you think it fixed something, it didn't.

You can check if a $digest is already in progress by checking $scope.$$phase.

if(!$scope.$$phase) {  //$digest or $apply}

$scope.$$phase will return "$digest" or "$apply" if a $digest or $apply is in progress. I believe the difference between these states is that $digest will process the watches of the current scope and its children, and $apply will process the watchers of all scopes.

To @dnc253's point, if you find yourself calling $digest or $apply frequently, you may be doing it wrong. I generally find I need to digest when I need to update the scope's state as a result of a DOM event firing outside the reach of Angular. For example, when a twitter bootstrap modal becomes hidden. Sometimes the DOM event fires when a $digest is in progress, sometimes not. That's why I use this check.

I would love to know a better way if anyone knows one.


From comments: by @anddoutoi

angular.js Anti Patterns

  1. Don't do if (!$scope.$$phase) $scope.$apply(), it means your $scope.$apply() isn't high enough in the call stack.


The digest cycle is a synchronous call. It won't yield control to the browser's event loop until it is done. There are a few ways to deal with this. The easiest way to deal with this is to use the built in $timeout, and a second way is if you are using underscore or lodash (and you should be), call the following:

$timeout(function(){    //any code in here will automatically have an apply run afterwards});

or if you have lodash:

_.defer(function(){$scope.$apply();});

We tried several workarounds, and we hated injecting $rootScope into all of our controllers, directives, and even some factories. So, the $timeout and _.defer have been our favorite so far. These methods successfully tell angular to wait until the next animation loop, which will guarantee that the current scope.$apply is over.