Search code examples
javascriptangularjsangularjs-ng-repeatangularjs-digest

ng-repeat call controller function too many times


I have next code (events is array):

<tr ng-repeat="event in events">
    <td>
        <span time-ago="{{event.TimestampSec}}"></span>
    </td>
    <td>
        {{prepareAlertValue(event.AlertValue)}}
    </td>
</tr>

time-ago - my custom directive. It is executed events.length times.

My controller:

...
window.callPrepareAlertValueCount = 0

$scope.prepareAlertValue = function(value) {
    window.callPrepareAlertValueCount++;
    if(safemineHelper.isFloat(value)) {
        value = (~~(value * 100)) / 100;
    }
    return value;
}
...

After list is shown - I see that callPrepareAlertValueCount grows. Console log:

 > callPrepareAlertValueCount
 < 41890
 > callPrepareAlertValueCount
 < 46150
 > callPrepareAlertValueCount
 < 480315

Please, can someone explain why is prepareAlertValue executed all time. Do I need to write directives for each formatter function?


Solution

  • That is correct what ever you bind on html, it gets called on each digest cycle run by angular js.

    Use {{::prepareAlertValue(event.AlertValue)}} bind once directive that will execute that function only once.

    Note Bind Once only work for above Angular 1.3+