ng-repeat中的函数不断循环

Function in ng-repeat keeps looping

本文关键字:循环 函数 ng-repeat      更新时间:2023-09-26

我正在使用ng-repeat加载项目列表。在其中一个字段中,我将从ng-repeat获得的ID传递给一个函数,以便从另一个数据库表中获取信息。当我这样做并console.log结果时,它只是不断循环。

<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);
    });
};

将 API 服务调用放在watchExpression中是一个非常糟糕的主意,因为 AngularJS 框架在每个摘要周期中调用该表达式。

从文档中:

每次调用 $digest() 时都会调用该watchExpression,并应返回将被监视的值。( watchExpression 在使用相同的输入多次执行时不应更改其值,因为 $digest() 可能会多次执行它。也就是说,watchExpression应该是幂等的。

--

AngularJS API 参考 -- $watch

重构代码以在控制器内执行 API 调用,缓存结果,并在监视表达式中使用类似 {{ cachedAmountQuestion[q.guid] }} 的内容。