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

综合技术 2018-02-14

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!

责编内容by:Hello, buddy! (源链)。感谢您的支持!

您可能感兴趣的

Stable AngularJS and Long Term Support – Angular B... Stable AngularJS and Long Term SupportAngularJS is planning one more significant release, versi...
Testing Angular: Techniques & Practices As writing tests for frontend has always been hard, this presentation shows you how to make software...
Error and Performance Monitoring for Web & Mob... Fixing a bug is a whole lot easier when you know how it occurred, but that may not always be the cas...
Custom angular circular progression bar SVG User I... I have developed my circular progress bar from angular-circular-progress github. My current inpu...
Version 5.0.0 of Angular Now Available We are pleased to announce version 5.0.0 of Angular, pentagonal-donut. This is a major release cont...