15

我需要sublist在页面的几个地方使用指令,它有时应该包含完整fields列表,但有时会被过滤。这是我天真的方法:

HTML:

  <div ng-controller="MainCtrl">
      <sublist fields="fields" /> <!-- This one is OK -->
      <sublist fields="fields | filter: 'Rumba'" /> <!-- This one raises error -->
  </div>

Javascript:

angular.module('myApp', [])
    .directive('sublist', function () {
        return {
            restrict: 'E',
            scope: { fields: '=' },
            template: '<div ng-repeat="f in fields">{{f}}</div>'
        };
    })
    .controller('MainCtrl', function($scope) {
        $scope.fields = ['Samba', 'Rumba', 'Cha cha cha'];
    });

http://jsfiddle.net/GDfxd/14/

当我尝试使用过滤器时,出现此错误:

Error: 10 $digest() iterations reached. Aborting!

这个问题有解决方案吗?

4

2 回答 2

24

The $digest iterations error typically happens when there is a watcher that changes the model. In the error case, the isolate fields binding is bound to the result of a filter. That binding creates a watcher. Since the filter returns a new object from a function invocation each time it runs, it causes the watcher to continually trigger, because the old value never matches the new (See this comment from Igor in Google Groups).

A good fix would be to bind fields in both cases like:

<sublist fields="fields" /></sublist>

And add another optional attribute to the second case for filtering:

<sublist fields="fields" filter-by="'Rumba'" /></sublist>

Then adjust your directive like:

return {
    restrict: 'E',
    scope: {
        fields: '=',
        filterBy: '='
    },
    template: '<div ng-repeat="f in fields | filter:filterBy">'+
              '<small>here i am:</small> {{f}}</div>'
};

Note: Remember to close your sublist tags in your fiddle.

Here is a fiddle

于 2013-06-19T19:39:54.253 回答
1

更正的小提琴

在此处查看相关帖子。

在小提琴中,您将需要有结束标签。虽然您仍然可以拥有像您拥有的那样的自包含标签。

 <sublist fields="fields" filter="'Rumba'"/> <!-- Tested in chrome -->
于 2013-06-19T20:19:23.040 回答