2

I have a scoped function that fires more times than is invoked and can't figure out why. I've created a small example in plunker and snippets appear below. when the page is loaded you would think that $scope.hex_color should fire three times but if you view the console in the debugger (Chrome F12) it fires nine times.

Can anyone explain?

http://plnkr.co/edit/7DMwA2InP0v6sD2s5WxW?p=preview

html snippet:

<div ng-repeat="shape in list">
    <div>{{ shape.Title }} | {{ hex_color(shape) }}</div>
</div>

controller snippet:

$scope.list = [
    { "Id": 1000, "Title": "Red Ball", "red": "ff", "green": "00", "blue": "00" },
    { "Id": 1001, "Title": "Green Triangle", "red": "00", "green": "ff", "blue": "00" },
    { "Id": 1002, "Title": "Blue Square", "red": "00", "green": "00", "blue": "ff" },
];
$scope.hex_color = function (shape) {
    $log.info("hex_color: " + shape.Id);
    return "#" + shape.red + shape.green + shape.blue;
}

enter image description here

Update: If I run the code in a local server (the above example was monitoring the code in plunker), it fires 15 times!

enter image description here

howardlo
  • 1,401
  • 1
  • 15
  • 20
  • 1
    possible duplicate of [Why angularjs will invoke function \`name()\` twice?](http://stackoverflow.com/questions/14973792/why-angularjs-will-invoke-function-name-twice) – JLRishe Feb 02 '15 at 09:58
  • See also: http://stackoverflow.com/questions/14987277/function-called-multiple-times-in-angularjs-repeat-section – JLRishe Feb 02 '15 at 09:59
  • I understand it now. Thanks JLRishe and squiroid for the answers! – howardlo Feb 02 '15 at 10:20

1 Answers1

1

From what I can tell, a filter is executed once during every $digest. This makes sense, when you think about how AngularJS manages its data bindings. Since AngularJS uses dirty-checking, it has to recheck all of its internal $watch() statements after "you" (as the programmer / user) do anything. After all, every interaction taken by the user may cause a change in the view-model which may, in turn, change the collection that is being filtered. As such, the filter has to be re-applied at the end of every $digest.

Source:- http://www.bennadel.com/blog/2489-how-often-do-filters-execute-in-angularjs.htm

squiroid
  • 13,809
  • 6
  • 47
  • 67