Controller function is called multiple times

I have done some research on both Google and StackOverflow and found several similar questions, but none of them address or address my particular case. So here's my question:

In some code I am working on, I am calling a controller function from my html, for example:

<div ng-controller="MyCtrl">
  <p>{{ myFunction() }}</p>
</div>

      

And since in myFunction I am doing some tracing, I noticed that the function is being called 4 times!

I created a minimal test in JS Bin, here: http://jsbin.com/nukuhemata/1/edit?html,js,console,output

In this minified test, my function is called 3 times (there is some progress ;-). And if instead {{ test() }}

I use {{ ::test() }}

as suggested in some of the other answers I've seen, it only gets called twice (another progress).

I'm new to Angular, from what I've read I think this is normal, expected behavior. This is true? If so, why? If not, what is wrong with my code?

+3


source to share


1 answer


This is normal behavior, every time the loop is executed $digest

, the function must be executed to check if the output value has changed, and therefore if there is a new value to update the DOM from.

Because of this, it is better to practice updating the value $scope

from the controller when needed and linking to that markup. This is usually not a significant difference, but if your function creates a large array for ng-repeat

, it can be a big problem.



Edit: See the function called multiple times from the template for a more robust answer.

+4


source







All Articles