我有一个简单的 Controller 函数,可以计算每个问题有多少个答案:
$scope.countAnswers = function(questionid) {
AnswersQueries.getAnswers(questionid, function(answers) {
var answersCount = answers.length;
return answersCount;
});
};
HTML
<!-- Inside ng-repeat -->
<div>{{countAnswers(question._id)}}</div>
服务
angular.module('app')
.factory('AnswersQueries', function ($resource) {
return {
getAnswers: function(questionId, callback) {
// Define resource
var data = $resource('api/answers?questionid=' + questionId);
// Fire the get call
data.query().$promise.then(function(answer){
// Return answer in callback
callback(answer);
});
}
};
});
当我尝试重新加载页面时,它会发出大量请求来计算问题......正确的请求,但它永远不会停止:
即...
GET /api/answers?questionid=54ae02aec07933920b000001 200 28ms - 371b
GET /api/answers?questionid=54aec71cdd9a29d210000001 200 28ms - 2b
GET /api/answers?questionid=54aec75bdd9a29d210000002 200 32ms - 2b
GET /api/answers?questionid=54adf9f0e0913a590a000001 200 7ms - 2b
GET /api/answers?questionid=54ae02aec07933920b000001 200 14ms - 371b
GET /api/answers?questionid=54aec71cdd9a29d210000001 200 4ms - 2b
GET /api/answers?questionid=54aec75bdd9a29d210000002 200 4ms - 2b
GET /api/answers?questionid=54aec75bdd9a29d210000002 200 15ms - 2b
GET /api/answers?questionid=54ae02aec07933920b000001 200 18ms - 371b
GET /api/answers?questionid=54aec71cdd9a29d210000001 200 17ms - 2b
GET /api/answers?questionid=54adf9f0e0913a590a000001 200 20ms - 2b
GET /api/answers?questionid=54ae02aec07933920b000001 200 17ms - 371b
GET /api/answers?questionid=54adf9f0e0913a590a000001 200 7ms - 2b
GET /api/answers?questionid=54aec71cdd9a29d210000001 200 9ms - 2b
控制台错误(我想我现在可以排除故障...之前没有看到这个,因为页面被卡住了):
Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: []
可能会发生什么?
最佳答案
我不确定它是否有助于解决问题,但您的 countAnswers
函数是错误的。
行returnanswersCount;
从回调函数返回。您实际的 countAnswers
函数不会返回任何内容。由于 AnswersQueries.getAnwers
是异步的,因此您无法立即使用其结果。
解决方案是将值存储在范围中并在回调中更新。
$scope.counts = {};
$scope.countAnswers = function(questionid) {
AnswersQueries.getAnswers(questionid, function(answers) {
$scope.counts[questionid] = answers.length;
});
};
//call $scope.countAnswers for each question in your scope *once*
html 应该如下所示:
<div>{{counts[question._id]}}</div>
关于javascript - AngularJS Controller 无限请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27852955/