Angular JS : $Scope.Apply()

元气小坏坏 提交于 2019-12-12 09:30:02

问题


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.


回答1:


$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.



来源:https://stackoverflow.com/questions/28689467/angular-js-scope-apply

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!