Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularjs - filter by multiple models

Tags:

angularjs

This seems like it must be simple, I just cannot find the answer.

Let's say I have an array of data, set out like the following:

friends = [{name:'John', age:60, location:'Brighton', street:'Middle Street'},
{name:'Bob', age:5, location:'Brighton', street:'High Street'}];

Now, I want to filter the data based on a text input like so:

<input ng-model="searchText">
<ul>
    <li ng-repeat="friend in friends | orderBy:'name' | filter:searchText">
    {{friend.name}} - {{friend.location}}</li>
</ul>

This works fine but it filters the input text based on every attribute of the friend object (name, age, location and street). I'd like to be able to filter based on name and location only (ignoring age and street). Is this possible without a custom filter?

like image 609
user2424495 Avatar asked Oct 11 '13 20:10

user2424495


Video Answer


1 Answers

Yes, it's possible by simply passing a predicate to the filter instead of a string:

<li ng-repeat="friend in friends | orderBy:'name' | filter:friendContainsSearchText">

$scope.friendContainsSearchText = function(friend) {
    return friend.name.indexOf($scope.searchText) >= 0 || friend.location.indexOf($scope.searchText) >= 0
}
like image 65
JB Nizet Avatar answered Nov 12 '22 05:11

JB Nizet