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?
-
Do you want to display it as Table and filter?Coder– Coder2015-05-28 12:24:38 +00:00Commented May 28, 2015 at 12:24
-
Yes I'm displaying it as a list in a table. currently using multiple input fields for that and ` ng-repeat="task in filtered = ( taskList | filter:query )` to display themEinius– Einius2015-05-28 12:26:54 +00:00Commented May 28, 2015 at 12:26
-
Can you create a plunkr or jsfiddle? So others can check it. It takes time to build from scratchCoder– Coder2015-05-28 12:31:23 +00:00Commented May 28, 2015 at 12:31
Add a comment
|
2 Answers
You would generally create your own filter for this:
Plunker Demo
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
}
};
});
Comments
You can chain the filters if you want. For example:
ng-repeat="item in items | filter:filterone| filter:filtertwo">