Search code examples
angularjsmeteorangular-meteor

ng-repeat too many iterations


I am using angular-meteor and would like to perform a function on each object. I tried running this function within an ng-repeat in the view, but I am getting massive amounts of function calls and can't figure out why. I tried to make it as simple as possible to demonstrate what is going on.

constructor($scope, $reactive) {
    'ngInject';
    $reactive(this).attach($scope);
    this.loaderCount = 0;

    this.helpers({
        loaders() {
            return Loaders.find( {isloader:true}, {sort: { name : 1 } })
        }
    });

That gives me 26 Loaders. My function just adds 1 to the count every time the function is called:

displayLoaderCount()
{
    return ++this.loaderCount;
}

Now in my view, I am looping through each loader, and calling the function. This should in my mind give me 26, but instead I am getting 3836.

 <tr ng-repeat="loader in loaderExhaustion.loaders">
        <td>{{loaderExhaustion.displayLoaderCount()}}</td>

Can anyone help explain this to me? Ideally I would like to loop over the contents in my module but as the collection is async, when the loop starts the length of the collection is 0, hence why I made the call in the view.

THANKS!


Solution

  • Every time angular enters a change detection cycle, it evaluates loaderExhaustion.displayLoaderCount(), to know if the result of this expression has changed, and update the DOM if it has. This function changes the state of the controller (since it increments this.loaderCount), which thus triggers an additional change detection loop, which reevaluates the expression, which changes the state of the controller, etc. etc.

    You MAY NOT change the state in an expression like that. For a given state, angular should be able to call this function twice, and get the same result twice. Expressions like these must NOT have side effects.

    I can't understand what you want to achieve by doing so, so it's hard to tell what you should do instead.