Angular通过其属性过滤对象 [英] Angular filter a object by its properties

查看:170
本文介绍了Angular通过其属性过滤对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有一系列对象属性的对象,它们具有以下类似结构(这是数据从服务返回的方式):

I have an object with a series of object properties that is in the following similar structure (which is the way the data is coming back from a service):

{
  "1": {
    "type": "foo",
    "name": "blah"
  },
  "2": {
    "type": "bar"
  },
  "3": {
    "type": "foo"
  },
  "4": {
    "type": "baz"
  },
  "5": {
    "type": "test"
  }
}

当我进行ng-repeat时,我可以迭代所有5个这些对象,例如:

When I do a ng-repeat, I can iterate over all 5 of these object, something like:

<div ng-repeat="item in items">{{item.type}}</div>

然而,我真正想要做的只是迭代那些不是键入foo,即3次迭代而不是5.我知道过滤器可以某种方式用来做到这一点,但我不知道如何。我尝试了以下方法:

However, what I really want to do is iterate only over those items that are NOT the type "foo", namely 3 iterations instead of 5. I know that filters can somehow be leveraged to do this, but I am not sure how. I tried the following:

<div ng-repeat="item in items| !filter:{type:'foo'}">{{item.type}}</div>

但这不起作用。实际上,即使只执行以下操作来限制只有2个对象(那些使用item.type ===foo),它也不起作用并进行5次迭代:

but this doesn't work. In fact, even doing the following to limit to just 2 objects(those with item.type==="foo"), it doesn't work and does 5 iterations:

<div ng-repeat="item in items| filter:{type:'foo'}">{{item.type}}</div>

本质上,我想做类似的事情:

In essence, I want to do something similar to:

<div ng-repeat="item in items" ng-if="item.type !=='foo'>{{item.type}}</div>

但是,我知道一个不起作用。

However, I know that one doesn't work.

推荐答案

过滤器适用于数组,但你有一个对象文字。

Filter works on arrays but you have an object literal.

所以你可以转换将对象文字放入数组或创建自己的过滤器而不是对象文字。

So you can either convert your object literal into an array or create your own filter than takes in the object literal.

如果您不需要这些索引值,那么转换为数组可能是您的最好的选择(
这是阵列工作的小提琴: http://jsfiddle.net/NqA8d/3/ ):

If you don't need those index values then converting to an array may be your best bet( Here's a fiddle with the array working: http://jsfiddle.net/NqA8d/3/):

$scope.items = [{
    "type": "foo",
        "name": "blah"
}, {
    "type": "bar"
}, {
    "type": "foo"
}, {
    "type": "baz"
}, {
    "type": "test"
}];

如果你想做一个过滤器,这是一种方法:

In case you'd like to do a filter, here's one way to do that:

myApp.filter('myFilter', function () {
    return function (items, search) {
        var result = [];
        angular.forEach(items, function (value, key) {
            angular.forEach(value, function (value2, key2) {
                if (value2 === search) {
                    result.push(value2);
                }
            })
        });
        return result;

    }
});

那个小提琴: http://jsfiddle.net/NqA8d/5/

这篇关于Angular通过其属性过滤对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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