Angular scope function executed twice when it should be run only once?

Demo here

Quick question: in the following code, I only call the isSpecificPage() function once, why is it twice in the .log console?

 <div ng-hide="isSpecificPage()"> <p>Hello!</p> </div> 
+1
source share
2 answers

Angular puts a clock on your ng-hide function so that each digest cycle can see if the results have changed (and therefore, if necessary, to hide, to show your item or vice versa).

When observable functions are evaluated (during $digest ), if any of them has changed from the previous $digest , then Angular knows that the change may pulse to other observable functions (perhaps the changed variable is used in another observable function). Therefore, each watch is reevaluated (also called dirty processing), until none of the watches change. Thus, as a rule, you will see 2 calls of the observed functions for the digest, and sometimes more (up to 10 - after 10 cycles it is reset through it and reports an error saying that it cannot stabilize).

Here's more on watch and digest :

http://docs.angularjs.org/api/ng . $ rootScope.Scope

http://www.benlesh.com/2013/08/angularjs-watch-digest-and-apply-oh-my.html

+5
source

ng-hide is one of the directives that uses $watch internally. Since $watch uses a digest loop (which runs at least 2 times to check if this value has changed), your isSpecificPage function runs twice.

For a list of directives that use $watch internally, refer to these directives > that have added hours inside themselves .

-1
source

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


All Articles