Reputation: 94
Refer below code.
Using angular filter i can search friend.name or friend.phone or both but how to make search in string that combines both, like in below example code i want to make a search for "mary - 80" and it should display only one list element "Mary - 800-BIG-MARY".
How to do this, pls help me out. Is it possible with using default angularjs filter??
<!doctype html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>
</head>
<body ng-app="">
<div ng-init="friends = [{name:'John', phone:'555-1276'},
{name:'Mary', phone:'800-BIG-MARY'},
{name:'Mike', phone:'555-4321'},
{name:'Adam', phone:'555-5678'},
{name:'Julie', phone:'555-8765'},
{name:'Juliette', phone:'555-5678'}]"></div>
<label>Search: <input ng-model="searchText"></label>
<li ng-repeat="friend in friends | filter: searchText">
<span>{{friend.name}} - {{friend.phone}}</span>
</li>
</body>
</html>
plunker link for same code: http://plnkr.co/edit/p7valhnDulHorw8xDYu8?p=preview
Upvotes: 3
Views: 216
Reputation: 5574
I think this will do what you want
change the repeat:
<li ng-repeat="friend in friends | filterText:searchText">
and then add this filter
app= angular.module("myApp",[]);
app.filter("filterText",function(){
return function(items,text){
var result = [];
text = text != undefined ? text : "";
var words = text.split(" ");
angular.forEach(items,function(v,i){
allFound = true;
angular.forEach(words,function(v2,i2){
if((v.name+v.phone).toUpperCase().indexOf(v2.toUpperCase())==-1){
allFound = false;
}
})
if(allFound)
result.push(v);
});
return result;
}
});
remember to add the ng-app
<body ng-app="myApp">
you dont need to use the '-' in your search, just use "Mary 800" or "Adam 555"
Upvotes: 0
Reputation: 4156
That's how angularJs filter works by default. If you want to filter by a specific combination of properties, then you have to implement your own filter function. Like here https://scotch.io/tutorials/building-custom-angularjs-filters
super simple example
$scope.customFilter = (item)=> {
//TODO: Add your own properties here
return item.someProperty == $scope.filterValue;
};
html
<htmlElement ng-repeat="item in itemList | filter:customFilter"></htmlElement>
Upvotes: 1