简体   繁体   中英

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.

Filter:

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

ng-repeat:

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

The problem comes when I want to filter the nested array ( 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.

It would be trivial to change the filter function to work based on length too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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