如何深入制作Angular'过滤器'滤镜?

时间:2014-07-17 14:03:59

标签: javascript angularjs

假设我在数组中有一些东西:

app.controller('ThingsController', function() {
    this.things = [
        {},
        {
            foo: 0,
        },
        {
            foo: -1,
            bar: null,  
        },
        {
            foo: 1,
            bar: { a: true, b: true },
        },
        {
            foo: 2,
            bar: { a: true, b: false },
        },
        {
            foo: 3,
            bar: { a: false, b: true },
        },
        {
            foo: 4,
            bar: { a: false, b: false },
        },
    ];
});

我希望显示这些内容,并能够根据某些选择条件过滤列表。我可能只希望显示那些foo == 2或其bar.a == true的内容。所以,我把它连接到这个HTML:

<div ng-init="filterObj = {};">
    foo: <input type="number" ng-model="filterObj.foo" />
    a: <input type="checkbox" ng-model="filterObj.bar.a" />
    b: <input type="checkbox" ng-model="filterObj.bar.b" />
    <input type="reset" ng-click="filterObj = {};" />

    <ul ng-controller="ThingsController as ctrl">
        <li ng-repeat="thing in ctrl.things | filter: filterObj"><!-- content --></li>
    </ul>
</div>

这样,对foo进行过滤就可以了,但bar上的过滤效果不正常,正如您在this jsfiddle中所看到的那样。具体来说,将filterObj.bar.afilterObj.bar.b设置为truefalse会使过滤器匹配任何真实bar。过滤filter: filterObj : true也不会有效,因为这会过滤完全深度相等(即filterObj = { bar: { a: true } }与上述任何内容都不匹配。)

如何深入进行此过滤,以便filterObj = { bar: { a: true } }与上述foo12而非其他内容的内容相匹配?我是否需要为此编写自己的过滤器或comparator,或者我可以使用一些技巧吗?

1 个答案:

答案 0 :(得分:1)

我使用自定义comparator让它工作。当我意识到这个确切的比较有an underscore function时,它变得更加简单。

app.controller('ThingsController', function() {
    this.things = [ /* ... */ ];

    this.filterComparator = function(actual, expected) {
        return _.matches(expected)(actual);
    };
});

HTML:

<li ng-repeat="thing in ctrl.things | filter: filterObj : ctrl.filterComparator"><!-- content --></li>
相关问题