Angular.js将过滤器传递给指令双向('=')属性

时间:2013-06-19 18:19:59

标签: javascript angularjs

我需要在页面的几个地方使用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!

这个问题有解决方案吗?

2 个答案:

答案 0 :(得分:24)

$ digest iterations 错误通常在存在更改模型的观察程序时发生。在错误情况下,隔离fields绑定绑定到过滤器的结果。该绑定创建了一个观察者。由于过滤器每次运行时都会从函数调用中返回一个新对象,因此它会导致观察者不断触发,因为旧值永远不会与新值匹配(参见this comment from Igor in Google Groups)。

一个好的解决方法是在两种情况下绑定fields,如:

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

并在第二种情况下添加另一个可选属性进行过滤:

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

然后调整你的指令,如:

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

注意:请务必关闭小提琴中的sublist标签。

Here is a fiddle

答案 1 :(得分:1)

Corrected Fiddle

检查相关帖子here

在小提琴中你需要有结束标签。 虽然你仍然可以拥有自己拥有的标签,但你可以拥有。

 <sublist fields="fields" filter="'Rumba'"/> <!-- Tested in chrome -->