我的 Angular 代码中出现以下错误。我很难理解为什么函数 getDrawWithResults 会导致摘要循环,因为它似乎没有任何副作用?它只返回列表中属性设置为 true 的项目。
错误仅在页面上第一次使用 getDrawWithResults 时发生,如果我删除,错误停止。
Uncaught Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: [["getDrawsWithResults(selectedLottery.draws); newVal: []; oldVal: []"],["getDrawsWithResults(selectedLottery.draws); newVal: []; oldVal: []"],["getDrawsWithResults(selectedLottery.draws); newVal: []; oldVal: []"],["getDrawsWithResults(selectedLottery.draws); newVal: []; oldVal: []"],["getDrawsWithResults(selectedLottery.draws); newVal: []; oldVal: []"]]
这是我的代码:
HTML
<h4 ng-cloak ng-hide="getDrawsWithResults(selectedLottery.draws)">Results of Selected Lottery</h4>
<div class="con" ng-repeat="draw in getDrawsWithResults(selectedLottery.draws)" ng-cloak>
<h5 class="con__header">[[ draw.date|date:'EEEE d MMMM yyyy - H:mm' ]]</h5>
<div class="balls-list__outer con__row">
<div class="balls-list">
<div class="balls-list__ball__outer" ng-repeat="b in draw.results">
<button class="balls-list__ball btn btn-con">[[ b ]]</button>
</div>
</div>
</div>
</div>
JS
// return list of draws with results
$scope.getDrawsWithResults = function(draws) {
return _.filter(draws, function(draw){
return draw.results && draw.results.length > 0;
});
}
最佳答案
我假设 _.filter
每次运行时都会返回一个新的数组实例。这会导致 Angular 的隐式 $watch
es 像:
ng-hide="getDrawsWithResults(selectedLottery.draws)"
和
ng-repeat="draw in getDrawsWithResults(selectedLottery.draws)"
想到模型变了,需要重新消化。
我会实现一个 filter
app.filter('withResults', function() {
return function(draws) {
return _.filter(draws, function(draw){
return draw.results && draw.results.length > 0;
});
}
})
并像那样应用它(见下面的编辑):
ng-hide="selectedLottery.draws | withResults"
和
ng-repeat="draw in selectedLottery.draws | withresults"
在评论中讨论后编辑
实际的问题是这个绑定(bind):
ng-hide="getDrawsWithResults(selectedLottery.draws)"
ng-hide
注册一个 watch,它将永远触发,因为过滤数组的引用总是会改变。可以改成:
ng-hide="getDrawsWithResults(selectedLottery.draws).length > 0"
和相应的过滤器:
ng-hide="(selectedLottery.draws | withResults).length > 0"
ng-repeat
没有同样的问题,因为它注册了一个$watchCollection
。
关于javascript - 没有范围变化时angularjs无限$ digest循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19863873/