arouse arouse - 1 year ago 78
AngularJS Question

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

Demo here

Quick question: in the following code I only call the function

once, why it console.log twice?

<div ng-hide="isSpecificPage()">

Answer Source

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:$rootScope.Scope

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download