Reputation: 643
I want to know more about $scope.apply() in real time usage. How many times can we use $scope.apply() in a controller?
For example, I have some events like ng-click() , ng-change(), ng-blur() etc. All events are in the same controller. For each and every event, should i use $scope.apply()? If yes, I am getting error :
Error: [$rootScope:inprog] [http://errors.angularjs.org/1.2.15/$rootScope/inprog?p0=%24apply][1]
at Error (native)
I have read in this forum that removing the addition $scope.apply() will resolve the issue.
angularjs $scope.$apply() gives this error: Error: [$rootScope:inprog]
I implemented the same solution of removing multiple $scope.apply() from the code. The errror is gone, but I want to know how and why?
Can anyone please explain.
Thanks in advance.
Upvotes: 0
Views: 2163
Reputation: 1063
$scope.apply()
is a trigger to update the DOM, and in most cases (such as a trigger from the DOM like ng-click
the evaluation of the trigger is wrapped in a $scope.apply()
as it is passed to your controller. You generally don't need to call $scope.apply()
as it is already being handled, but if you are having issues with something not updating correctly, you can use $scope.apply()
to basically nudge it to update. In order to prevent calling apply when apply is already being evaluated you can do a safe check like so:
if (!$scope.$$phase)
$scope.apply();
The $$phase
is an angular internal property that is null/undefined when no scope apply is in progress, and has a value when a $scope.apply()
is executing.
$scope.apply()
works by finding the most child scope (the innermost scope) and checking for changes, calling watches, etc, then it crawls up the scopes until it gets to the root scope, so as you might imagine it is a rather heavy call and should be avoided when possible.
Upvotes: 5