将筛选后的集合传递给Angular指令会导致异常

Passing a filtered collection to an Angular directive causes an exception

本文关键字:指令 Angular 异常 筛选 集合      更新时间:2023-09-26

我使用的是Angular,我要做的是将一个过滤后的集合传递给一个指令。

我的观点是这样的:

<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

p.S。我已经在Plunker上传了我的例子,一切似乎都在那里工作。我已经检查了我的应用程序中的代码是否相同。那么,为什么会发生这种情况呢?我的代码在Plunker上运行,但不在我的真实应用程序中。

您实际上并没有在指令中进行筛选;您正在将filterPeople语句中的筛选数据传递到用于显示的指令中。应用程序崩溃是因为你有一个ng重复影响另一个ng循环的输出,导致无限循环(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'
        }
    }
});