I have done some research both at Google and StackOverflow, and found several similar questions, but none seem to solve nor address my specific case. So here is my question:
In some code I am working on I am calling a controller function from my html, like this:
<div ng-controller="MyCtrl">
<p>{{ myFunction() }}</p>
</div>
And since in myFunction I do some tracing, I noticed the function gets called 4 times!
I have created a minimalistic test at JS Bin, here: http://jsbin.com/nukuhemata/1/edit?html,js,console,output
In this reduced test, my function gets called 3 times (there is some progress ;-). And if instead of {{ test() }} I use {{ ::test() }} as suggested in some other answers I have seen, it gets called only twice (some more progress).
I am a beginner at Angular, from what I have read I think it is the normal, expected behavior. Is that so? If it is, why? If not, what is wrong in my code?
It's normal behavior, every time a $digest cycle runs, the function must be executed to check whether the output value has change, and thus whether there's a new value to update the DOM with.
Because of this, it's better practice to update a value on the $scope from the controller when needed, and reference that in your markup. Usually not a meaningful difference, but if your function is building up a large array for a ng-repeat, it can become a big deal.
Edit: See function called multiple times from template for a more robust answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With