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));
});
}
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 });
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.
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.
$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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With