加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

AngularJS:过滤重复匹配列表

发布时间:2020-12-17 07:58:43 所属栏目:安全 来源:网络整理
导读:我有一个由ngRepeat循环的对象列表: hashes = [ { "type": "foo",… },{ "type": "foo",{ "type": "bar",… }] 如果它的值与针列表中的项匹配,我想根据类型过滤它们: types = ['foo','quz']; 所以像 div ng-repeat="hash in hashes | filter:types"/div 这
我有一个由ngRepeat循环的对象列表:
hashes = [
  {
      "type": "foo",…
  },{
      "type": "foo",{
      "type": "bar",…
  }
]

如果它的值与针列表中的项匹配,我想根据类型过滤它们:

types = ['foo','quz'];

所以像

<div ng-repeat="hash in hashes | filter:types"></div>

这是内置到Angular还是我必须编写自定义过滤器?

要过滤单一类型,您可以执行以下操作:
<div ng-repeat="hash in hashes | filter: {type:'foo'}">

要过滤数组,您不需要完全自定义的过滤器,但我会使用谓词过滤器,您可以将其传递给Angular的过滤器.这是过滤器,假设您的数组类型:

$scope.filterArray = function(hash) {
    return ($scope.types.indexOf(hash.type) !== -1);
};

像这样使用:

<div ng-repeat="hash in hashes | filter: filterArray">

两者都是demo fiddle

自订过滤器

要完成自定义过滤器,这可以:

filter('inArray',function() {
    return function inArray( haystack,needle ) {
        var result = [];
        var item,i;
        for (i=0; i< haystack.length;i++) {
            item = haystack[i];
            if (needle.indexOf(item.type) !== -1)
              result.push(item);
        };
        return (result);
    };
});

像这样使用:

<div ng-repeat="hash in hashes | inArray: types">

demo of custom filter

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读