0

我正在使用 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

PS 我已经在Plunker上传了我的示例,一切似乎都在那里工作。我检查了我的应用程序中的代码是否相同。那么,为什么会这样呢?我的代码在Plunker上运行,但不在我的真实应用程序中。

4

1 回答 1

1

您实际上并没有在指令中过滤;您正在将过滤后的数据从您的 filterPeople 语句传递到用于显示的指令中。应用程序崩溃,因为您有一个 ng-repeat 影响另一个 ng-repeat 的输出,导致无限循环(Angular 在 10 次递归后终止循环)

Plunkr here 展示了解决此问题的正确方法。只需将您的过滤器拉入您的指令。

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'
        }
    }
});
于 2015-10-30T12:43:24.033 回答