Angular.js通滤波器,以指令双向(“=”)属性 [英] Angular.js pass filter to directive bi-directional ('=') attribute

查看:144
本文介绍了Angular.js通滤波器,以指令双向(“=”)属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用子列表指令在页面的几个地方,它应该包含有时全字段列表的,但有时过滤。这里是我的幼稚的做法:

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?

推荐答案

$消化迭代的错误通常发生在有改变模型中的守望者。在错误的情况下,分离字段被绑定到一个过滤器的结果。该绑定创建一个观察者。由于过滤器返回从每次运行时函数调用一个新的对象,它会导致观察者不断触发,因为旧的价值永远不匹配的新的(见的从伊戈尔在谷歌群组这个评论)

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.

这里是一个小提琴

这篇关于Angular.js通滤波器,以指令双向(“=”)属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆