Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: $digest already in progress

I'm getting this error while trying to call

        function MyCtrl1($scope, $location, $rootScope) {       $scope.$on('$locationChangeStart', function (event, next, current) {         event.preventDefault();         var answer = confirm("Are you sure you want to leave this page?");         if (answer) {           $location.url($location.url(next).hash());           $rootScope.$apply();         }       });     }  MyCtrl1.$inject = ['$scope', '$location', '$rootScope']; 

Error is

Error: $digest already in progress 
like image 806
iJade Avatar asked Feb 12 '13 17:02

iJade


People also ask

How do you resolve $Digest already in progress?

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 });

What is $apply in AngularJS?

In AngularJS, $apply() function is used to evaluate expressions outside of the AngularJS context (browser DOM Events, XHR). Moreover, $apply has $digest under its hood, which is ultimately called whenever $apply() is called to update the data bindings.

What is $timeout in AngularJS?

This '$timeout' service of AngularJS is functionally similar to the 'window. setTimeout' object of vanilla JavaScript. This service allows the developer to set some time delay before the execution of the function.

What is rootScope digest?

$rootScope.$digest() This is used to call watcher for the entire scope. It is equivalent to $scope. $apply() with no optional function expression.


1 Answers

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

That error you are getting means Angular's dirty checking is already in progress.

Most recent best practices say that we should use $timeout if we want to execute any code in the next digest iteration:

$timeout(function() {   // the code you want to run in the next digest }); 

Previous response: (don't use this approach)

Use a safe apply, like this:

$rootScope.$$phase || $rootScope.$apply(); 

Why don't you invert the condition?

$scope.$on('$locationChangeStart', function (event, next, current) {                     if (confirm("Are you sure you want to leave this page?")) {         event.preventDefault();     } }); 
like image 76
bmleite Avatar answered Oct 05 '22 23:10

bmleite