What does $ scope mean. $ apply () is not high enough on the call stack in this anti-pattern

I am reading this document, which presents anti-patterns, and there is the following: Do not execute if (!$scope.$$phase) $scope.$apply() , this means that your $scope.$apply() not high enough in the call stack. Can someone explain to me what this means?

I'm particularly interested in the part isn't high enough in the call stack . I know what $$phase and $apply and why it is used. It would be great to see that an example area is not high enough on the stack.

+5
source share
2 answers

A call stack is a chain of calls made by a specific function, for example, what you can see inside the console when a javascript error occurs. for instance

  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.<anonymous> (site/bower_components/angular-touch/angular-touch.js:437:13) 

This is a call stack. Now the $ apply () function should be called when the entire function loop is complete, so it says that it should be at the highest level of the call stack. Because you need to be sure that every process is executed in order to make $ apply () safe, also because, as you know, you cannot do 2 digest cycles in the same $ area 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 call to $ apply () should be inside func a (), being the very highest level of the call stack.

+1
source

This means that you see if (! $ Scope. $$ phase) $ scope. $ apply () is somewhere in your code, then something is probably wrong. Because in the optimal situation you do not need to check $ scpoe. $$ phase. $$ phase is a property that angular uses internally and should not be used in application code. The $$ phase is the base value of a boolean property that indicates that the $ digest loop is already running (angular uses it to check for model updates). If you call $ apply, you will tell angular to start the $ digest phase (check for model updates). You must do this manually only if you want to update the model outside of angular code (for example, in jquery plugin handlers).

I recommend reading this wonderful article if you want to learn angular from the inside: http://teropa.info/blog/2013/11/03/make-your-own-angular-part-1-scopes-and-digest.html

0
source

Source: https://habr.com/ru/post/1203480/


All Articles