Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
332 views
in Technique[技术] by (71.8m points)

javascript - Angular.js pass filter to directive bi-directional ('=') attribute

I need to use sublist directive in few places of the page, and it should contain sometimes full fields list, but sometimes filtered. Here is my naive approach:

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/

When I try to use filter I'm getting this error:

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

Is there a solution for this problem?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...