我正在使用 Angular,我想做的是将过滤后的集合传递给指令。
我的 View 如下所示:
<h1>Filtered Collection (no directive)</h1>
<ul>
<li ng-repeat="person in filteredPeople = (people | filter: { isChecked: true })">
{{ person.name }}
</li>
</ul>
我传递的数据只是一个简单的对象数组:
$scope.people = [
{
name: "George",
isChecked: false
},
{
name: "Jane",
isChecked: false
},
{
name: "Peter",
isChecked: true
}
];
到目前为止一切正常。但是当我尝试将上面的 HTML 放入指令中时,应用程序崩溃了。
指令:
myApp.directive('filterPeople', function () {
return {
restrict: 'A',
template: '<h1>Filtered Collection (directive)</h1>' +
'<ul>' +
'<li ng-repeat="item in collection">{{ item.name }}</li>' +
'</ul>',
scope: {
collection: '=collection'
}
}
});
查看:
<div filter-people collection="filteredPeople"></div>
我得到的错误:
Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations
附注 我已将示例上传到 Plunker一切似乎都在那里进行。我检查了我的应用程序中的代码是否相同,确实如此。那么,为什么会发生这种情况呢?我的代码运行于 Plunker但在我真正的应用程序中却没有。
最佳答案
您实际上并没有在指令中进行过滤;您正在将过滤后的数据从 filterPeople 语句传递到指令中进行显示。应用程序崩溃是因为一个 ng-repeat 影响了另一个 ng-repeat 的输出,导致无限循环(Angular 在 10 次递归后终止循环)
Plunkr 此处展示了解决此问题的正确方法。只需将过滤器拉入指令即可。
http://plnkr.co/edit/avjr306MESGE8xE6yN1M?p=preview
myApp.directive('filterPeople', function() {
return {
restrict: 'A',
template: '<h1>Filtered Collection (directive)</h1>' +
'<ul>' +
'<li ng-repeat="item in collection | filter: { isChecked: true }">{{ item.name }}</li>' +
'</ul>',
scope: {
collection: '=collection'
}
}
});
关于javascript - 将过滤后的集合传递给 Angular 指令会导致异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33436133/