在AngularJS中一起过滤多个对象属性

时间:2015-04-27 15:17:13

标签: angularjs angularjs-filter

我的控制器中有一个对象

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.names = [{"Name":"Alfreds Futterkiste","City":"Berlin","Country":"Germany"}, 
{"Name":"Ana Trujillo Emparedados y helados","City":"México D.F.","Country":"Mexico"}, 
{"Name":"Antonio Moreno Taquería","City":"México D.F.","Country":"Mexico"},
 {"Name":"Around the Horn","City":"London","Country":"UK"}, 
{"Name":"B's Beverages","City":"London","Country":"UK"}];
});

我想同时过滤NameCountry

Name:<input type="text" ng-model="name"> 
Country:<input type="text" ng-model="country"> <br>
 <table>
<tr ng-repeat="x in names | filter: name | filter: country">
   <td>{{ x.Name }}</td>
   <td>{{ x.Country }}</td>
</tr>
</table>

但两个输入框都在两列上都应用了过滤器。

如何仅将name输入设置为第一列和country输入,仅设置为第二列?

3 个答案:

答案 0 :(得分:3)

要过滤特定属性foo,您需要传递一个包含要匹配的字符串属性foo的对象。

Name:<input type="text" ng-model="criteria.Name"> 
Country:<input type="text" ng-model="criteria.Country"> <br>

<table>
<tr ng-repeat="x in names | filter: criteria">
   <td>{{ x.Name }}</td>
   <td>{{ x.Country }}</td>
</tr>
</table>

答案 1 :(得分:1)

我找到了答案。我所要做的就是将html部分更改为此

Name:<input type="text" ng-model="name.Name"> 
Country:<input type="text" ng-model="country.Country"> <br>
 <table>
<tr ng-repeat="x in names | filter: name | filter: country">
   <td>{{ x.Name }}</td>
   <td>{{ x.Country }}</td>
</tr>
</table> 
</div>

答案 2 :(得分:1)

我们可以使用这样的任意数量的财产:

<tr ng-repeat="item in filtered = (names | filter : {Name : name, 
                  City: city, 
                  Country: country })">

See the demo on codepen

或者我们可以使用该对象,但确保在创建对象时,对象中的ng-model属性和结果中的属性必须与名称和大小写匹配,并使用JB Nizet建议的逻辑

假设我要搜索所有三个属性名称,城市和国家,然后我将创建像这样的HTML

<div class='form-group'>
    <div class='row'>
       <div class="right-inner-addon col-md-4 ">        
        <input type="search" ng-model='model.Name' class="form-control" placeholder="Name">
       </div>
       <div class="right-inner-addon col-md-4 ">        
        <input type="search" ng-model='model.City' class="form-control" placeholder="City">
      </div>
       <div class="right-inner-addon col-md-4 ">        
        <input type="search" ng-model='model.Country' class="form-control" placeholder="Country">
      </div>
    </div>
</div>

我可以像

一样使用过滤器
<tr ng-repeat="item in filtered = (names | filter : model)">

See the working demo here

其他filter tricks see