Reputation: 1612
I have a data object full of data being used on my page however, within one section I want it to be filterable. I want to have one input field which filters through the data, but I want to be able to select the fields in which I filter by and it not be all of the data within the object.
I have made a quick example here http://plnkr.co/edit/huuZ0q0B0ijogXL9ThnX?p=preview
<div ng-init="friends = [{
random:{
tv: 'bbc'
},name:'John', phone:'555-1276'},
{random:{
tv:'bbc'},name:'Mary', phone:'800-BIG-MARY'},
{random:{
tv:'itv'},name:'Mike', phone:'555-4321'},
{random:{
tv:'itv'},name:'Adam', phone:'555-5678'},
{random:{
tv:'itv'},name:'Julie', phone:'555-8765'},
{random:{
tv:'itv'},name:'Juliette', phone:'555-5678'}]"></div>
Search: <input ng-model="searchText">
<table id="searchTextResults">
<tr><th>Name</th><th>Phone</th></tr>
<tr ng-repeat="friend in friends | filter:searchText">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
</tr>
</table>
I have added a key called random, which contains tv (such as a value of bbc) now if you enter bbc into the input field they all show however, I only want to search name and/or phone.
Any help on this would be greatly appreciated.
Upvotes: 0
Views: 86
Reputation: 123739
You could probably create a custom filter, i believe or
is not supported for multiple keys with the default filter.
angular.module('app',[]).filter('customFilter', function(){
return function(input, searchText){
if(!angular.isArray(input)) return;
var exp = new RegExp(searchText, 'ig');
return input.filter(function(inp){
return exp.test(inp.name) || exp.test(inp.phone);
});
}
});
Or a more generic one where you can pass keys to search for:-
angular.module('app',[]).filter('customFilter', function(){
return function(input, searchText, fields){
if(!angular.isArray(input)) return;
var exp = new RegExp(searchText, 'ig');
fields = fields.split(',');
return input.filter(function(inp){
return fields.some(function(key){
return exp.test(inp[key])
});
});
}
});
and use as:
<tr ng-repeat="friend in friends | customFilter:searchText:'name,phone'">
See compatibility and polyfill for Array.prototype.some
Upvotes: 2