What is `$ scope. $ Apply () is not high enough in the…

I’m reading through this document which presents anti-patterns and there is the following there: Don’t do if (!$scope.$$phase) $scope.$apply()
, it means your $scope.$apply()
isn’t high enough in the call stack. Can anyone please explain me what that means?

I’m specifically interested in the isn't high enough in the call stack
part. I know what $$phase
and $apply
is and why it is used. It would be great to see an example of scope being not high enough in stack.

The call stack is the chain of calls made by a certain function, like what you can see inside the console when ther’s a javascript error. For example

at Scope.$scope.openRightMenu (site/header.ctr.js:19:12)
        at Parser.functionCall (site/bower_components/angular/angular.js:10567:21)
        at site/bower_components/angular-touch/angular-touch.js:438:9
        at Scope.$get.Scope.$eval (site/bower_components/angular/angular.js:12412:28)
        at Scope.$get.Scope.$apply (site/bower_components/angular/angular.js:12510:23)
        at HTMLDivElement. (site/bower_components/angular-touch/angular-touch.js:437:13)

This is a call stack. Now the $apply() func must be called when the entire function cycle is finished, that’s why it says that it should be in the highest level of the call stack. Because you have to be sure that every process is done in order to make a safe $apply() also because, as you know, you cannot make 2 digest cycles on the same $scope at once.

So if you have

func a() -> calling -> func b() //setting $scope elaborated data
func b() -> calling -> func c() //elaborating data
func c() -> calling -> func d() //getting data

Your $apply() call should be inside func a(), being that the highest level of your call stack.

Hello, buddy!稿源:Hello, buddy! (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 前端开发 » What is `$ scope. $ Apply () is not high enough in the…

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录