简体   繁体   English

按数组长度或AngularJS中的嵌套对象属性过滤

[英]Filter by array length or nested object property in AngularJS

I have an array with objects looking like that: 我有一个对象看起来像这样的数组:

record in recordlist {
    date : "02/12/2014"
    time : "00.02.01"
    car : "369"
    pax: [
        {
        name : "Ben"
        chosen : true
        },
        {
        name : "Eric"
        chosen : true
        }
    ]
}

So far, when I list using ng-repeat, I'm able to filter by object (record) property. 到目前为止,当我使用ng-repeat进行列表时,我可以按对象(记录)属性进行过滤。

Filter: 过滤:

<input class="form-control" placeholder="Time" ng-model="search.time">

ng-repeat: NG-重复:

<div ng-repeat="record in filteredRecords = (recordlist | filter: search)">

The problem comes when I want to filter the nested array ( pax ). 当我要过滤嵌套数组( pax )时,问题就来了。 I've tried this, but so far no luck: 我已经尝试过了,但是到目前为止还没有运气:

<input ng-model="search.pax.name"> // filter by name property

<input ng-model="search.pax.length"> // filter by array length

Any tips? 有小费吗?

You will probably need to use a custom filter: 您可能需要使用自定义过滤器:

Something like this should do it: 这样的事情应该做到:

<input ng-model="searchName">

<div ng-repeat="record in recordlist | filter: filterByNested">

And in your controller: 在您的控制器中:

$scope.filterByNested = function (record) {
    return record.pax.reduce(function (prev, curr, idx, array) {
        return prev || curr.name == $scope.searchName;
    }, false);
};

Basically you define a custom filter that returns true if the element you are searching is in the nested array. 基本上,您定义了一个自定义过滤器,如果要搜索的元素在嵌套数组中,则返回true。

It would be trivial to change the filter function to work based on length too. 也将过滤器功能更改为基于长度也很简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM