Angular:如何按数组中的深层对象属性进行过滤?

时间:2015-07-20 16:44:13

标签: javascript angularjs filter

我有一个像这样的对象:

id: 1,
name: MyObj
properties: {
  owners: [
  {
    name:owner1,
    location: loc1
  },
  {
    name:owner2,
    location: loc1
  }
 ]
}

每个对象的所有者数量不同。当我尝试使用带有ng-repeat的{​​{1}}和搜索框输入

过滤它时
filter:searchBox

按标题过滤效果很好,但是所有者过滤根本不起作用,但我认为它会根据位置和名称进行过滤。我做错了什么?

2 个答案:

答案 0 :(得分:1)

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {

$scope.objs = 
  {
    id: 1,
    name: 'MyObj',
    properties: {
      owners: [
      {
        name: 'owner1',
        location: 'loc1'
      },
      {
        name: 'owner2',
        location: 'loc2'
      }
     ]
    }
  };

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">

<input name="search-filter" class="form-control" type="search" placeholder="Search by location" ng-model="searchBox.properties.location" />
<input name="search-filter" class="form-control" type="search" placeholder="Search by name"   ng-model="searchBox.properties.owners" />
 
  <div ng-repeat="owner in objs.properties.owners | filter:{'location': searchBox.properties.location} |filter:{'name': searchBox.properties.owners}">
    {{owner}}
    
  </div>

</div>

答案 1 :(得分:0)

您可以手动过滤

var list = [
  {
    id: 1,
    name: 'MyObj',
    properties: {
      owners: [
      {
        name: 'owner1',
        location: 'loc1'
      },
      {
        name: 'owner2',
        location: 'loc1'
      }
     ]
    }
  }
];

function filter(filter) {
  return list.filter(function(item) {
    return item.properties.owners.find(function(owner) {
      return Object.keys(filter).every(function(key) {
        return filter[key] === owner[key];
      });
    });
  });
}

console.log(filter({ name: 'owner1', location: 'loc1' }));

我使用了es6垫片。