Reputation: 54
I have a small list and want to execute a function for each list item. But this function gets executed multiple times and I don't know why.
HTML:
<body ng-controller="ListCtrl">
<div>
<ul ng-repeat="item in items">
<li>{{item.name}}<img ng-src="{{test()}}"></li>
</ul>
{{counter}}
</div>
</body>
Angular:
$scope.items = [
{name: 'foo', },
{name: 'bar', },
{name: 'baz', }
];
var counter= 0;
$scope.test= function(){
$scope.counter=counter++;
console.log("Executed");
}
Why is the function text executed multiple times? Also see this example: http://plnkr.co/edit/kxJZHCmFs4POd3SVtGZ8
Upvotes: 2
Views: 1393
Reputation: 6143
This is an expected behavior. Whenever an interpolation expression {{}}
is met in html template there is a watch created to track changes in that expression. During a $digest
cycle the expression can be evaluated dozens of times.
Never use function calls in interpolation expressions. Only reference properties defined in $scope
. In your case it should be something like
$scope.testValue = $scope.test();
{{testValue}}
Upvotes: 3