1

Demo here

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

<div ng-hide="isSpecificPage()">
  <p>Hello!</p>
</div>
KayakDave
  • 24,636
  • 3
  • 65
  • 68
Alex G
  • 1,321
  • 1
  • 24
  • 31

2 Answers2

6

Angular puts a watch on your ng-hide function so that every digest cycle it can see if the results changed (and thus if it needs to change from hiding to showing your element or vice-versa).

When watched functions are evaluated (during $digest) if any of them have changed from the previous $digest then Angular knows that change might ripple through to other watched functions (perhaps the changed variable is used in another watched function). So every watch is re-evaluated (also called dirty processing) until none of the watches results in a change. Thus typically you'll see 2 calls to watched functions per digest and sometimes more (up to 10- at 10 loops through it gives up and reports an error saying it can't 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

Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80
KayakDave
  • 24,636
  • 3
  • 65
  • 68
  • thanks, and I wonder if there's a way to reduce the times, that is am I able to only run the function once? – Alex G Nov 15 '13 at 04:21
  • Not within an `ng-hide`. Angular needs this mechanism so it can change the visibility of your element whenever the results of your conditional change. What's your motivation for fewer calls? – KayakDave Nov 15 '13 at 04:25
-1

ng-hide is one of the directives that uses $watch internally. Since $watch uses digest cycle(which runs atleast 2 times to check if the value has changed or not), so your function isSpecificPage has run twice.

For a list of directives that use $watch internally, refer this stackoverflow answer directives that add watch internally.

Community
  • 1
  • 1
madhu sudhan
  • 177
  • 1
  • 14