Reputation: 1382
How do I filter angularJS objects with a single field by multiple values?
Lets say object contains of person.id
person.firstName
person.LastName
person.birthday
what I want is to have a single search field to filter by person.firstName
or person.lastName
or person.id
but do not filter by person.birthday
how do I achieve that?
Upvotes: 1
Views: 2829
Reputation: 17372
You would generally create your own filter for this:
MARKUP:
<body ng-controller="MainCtrl">
<label>Search:
<input ng-model="searchString" />
</label>
<div ng-repeat="person in persons | byFullName: searchString ">{{person.id}}. {{person.LastName}}, {{person.firstName}}: {{person.birthday}}</div>
</body>
JS:
var app = angular.module('filter.demo', []);
app.controller('MainCtrl', ['$scope', function($scope){
$scope.persons = [
{id: 1, firstName: 'John', LastName: 'Doe', birthday: '01/02/2000'},
{id: 2, firstName: 'Jane', LastName: 'Smith', birthday: '03/02/2001'},
{id: 3, firstName: 'Mark', LastName: 'Johnson', birthday: '01/25/2001'},
{id: 4, firstName: 'Karen', LastName: 'Smith', birthday: '04/02/2000'},
{id: 5, firstName: 'John', LastName: 'Marker', birthday: '01/18/2003'}
];
}]);
app.filter('byFullName', function() {
return function(names, search) {
//names is the array that is passed to the filter
//search is the comparison value passed to the filter
if(angular.isDefined(search)) {
//make sure search is not undefined
var results = [];
var i;
var searchVal = search.toLowerCase();
for(i = 0; i < names.length; i++){
var firstName = names[i].firstName.toLowerCase();
var lastName = names[i].LastName.toLowerCase();
//*OPTIONAL: convert values to lowercase for case insensitive filter
if(firstName.indexOf(searchVal) >=0 || lastName.indexOf(searchVal) >=0){
//Loop over the array and check if the search string matches either
//the firstName or LastName
results.push(names[i]);
//If there's a match, add the value to the results array that is returned
}
}
return results;
} else {
return names;
//If no search value is provided, we just want to return the whole array
}
};
});
Upvotes: 1
Reputation: 18099
You can chain the filters if you want. For example:
ng-repeat="item in items | filter:filterone| filter:filtertwo">
Upvotes: 0