Greg
Greg

Reputation: 1402

Function in ng-repeat keeps looping

I'm loading a list of items using ng-repeat. In one of the fields I pass the ID I get from the ng-repeat to a function to get info from another database table. When I do this and console.log the result, it just keeps looping.

<ion-slide-box ng-repeat="q in questions.list track by $index">
      <ion-slide class="default box">
        <div class="amount">{{ getAmountQuestion(q.guid) }}</div>
        <div class="question"><h5>{{ q.fields.question }}</h5></div>
      </ion-slide>
</ion-slide-box>


$scope.getQuestionAmount = function(id) {
    QuestionsService.getAllVotesById(id).then(function (data) {
        console.log(data.count);
    });
};

Upvotes: 2

Views: 149

Answers (1)

georgeawg
georgeawg

Reputation: 48968

Putting an API service call inside a watchExpression is a really bad idea because the AngularJS framework calls that expression on every digest cycle.

From the Docs:

The watchExpression is called on every call to $digest() and should return the value that will be watched. (watchExpression should not change its value when executed multiple times with the same input because it may be executed multiple times by $digest(). That is, watchExpression should be idempotent.

-- AngularJS API Reference -- $watch

Refactor your code to execute the API calls inside the controller, cache the results, and in your watch expression use something like {{ cachedAmountQuestion[q.guid] }}.

Upvotes: 2

Related Questions