角过滤通过它一个对象的属性 [英] Angular filter a object by it's properties

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

问题描述

我有一系列对象属性的是在下面的类似的结构(这是数据从服务回来的方式)的对象

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-重复,我可以遍历这些对象的所有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>

然而,我真正想要做的只是在那些不是那种富项目是迭代,即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对象(那些用项目。形式===富),这是行不通的,并做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/

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

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