Search code examples
angularjsangularjs-filter

Filter multiple object properties together in AngularJS


I have an object in my controller

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"}];
});

I want to filter Name, Country at the same time.

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>

But both input boxes apply filter on both columns.

How to set the name input only to the first column and the country input, only to the second column?


Solution

  • To filter on a specific property foo, you need to pass an object which has a property foo containing the string to match.

    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>