Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: $digest already in progress in angularjs when using alert

Tags:

angularjs

I am just getting the json data from the services in the controller.

And I am using a callback function to print the success message when it got loaded. It is working fine but it is also throwing an error which I mentioned in the question

//JSON file
{
"pc":"name"
}

// angular services
var service = angular.module('Services', ['ngResource']).
factory('Widgets', function($resource){
    return $resource('/json/home.json', {}, {
        query: {method:'GET', params:{}, isArray:false}
    });
});

//controller
function editWidget($scope, Widgets) {
 $scope.data = Widgets.query(function(data) {   
    alert("Success Data Loaded ---> " + JSON.stringify(data.pc));
 });
}
like image 413
JSAddict Avatar asked May 03 '13 03:05

JSAddict


People also ask

How do you fix $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 $Digest in AngularJS?

In angularjs $digest() function is a central function of $scope object and it is used to iterate through the watch list items and check if any variable value has been modified or not.

When to use $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 the difference between Digest () and apply () Why would you ever call Digest () on a scope?

$digest() gets called without any arguments. $apply() takes a function that it will execute before doing any updates. The other difference is what they affect. $digest() will update the current scope and any child scopes.


2 Answers

alert, as well as confirm and prompt will pause the execution of code (blocks the thread), during which timeouts and intervals go all haywire if they should have been triggered during the pause. The $digest loop is made up of two smaller loops, which process $evalAsync queue and the $watch list. The $evalAsync queue is used to schedule work which needs to occur outside of current stack frame, but before the browser's view render. This is usually done with setTimeout(0). Your alert during this time causes the problem.

like image 123
TheSharpieOne Avatar answered Oct 20 '22 08:10

TheSharpieOne


You can use $timeout to execute an alert after the digest cycle is done and this way avoids this error.

$timeout(function () {
    alert('Alert text');
 }); 

Also don't forget to inject $timeout into your directive

like image 26
tylik Avatar answered Oct 20 '22 08:10

tylik