Wind Up Toy Wind Up Toy - 4 months ago 25
AngularJS Question

Filtering by Multiple Specific Model Properties in AngularJS (in OR relationship)

Take a look at the example here: http://docs.angularjs.org/api/ng.filter:filter

You can search by any of the phone properties by using

<input ng-model="search">
and you can search by just the name by using
<input ng-model="search.name">
, and the results are appropriately filtered by name (typing in a phone number does not return any results, as expected).

Lets say I have a model with a "name" property, a "phone" property, and a "secret" property, how would I go about filtering by both the "name" and "phone" properties and not the "secret" property? So in essence, the user could type a name or phone number and the
ng-repeat
would filter correctly, but even if the user typed in a value that equaled part of a "secret" value, it wouldn't return anything.

Thanks.

Answer

Here is the plunker

New plunker with cleaner code & where both the query and search list items are case insensitive

Main idea is create a filter function to achieve this purpose.

From official doc

function: A predicate function can be used to write arbitrary filters. The function is called for each element of array. The final result is an array of those elements that the predicate returned true for.

<input ng-model="query">

<tr ng-repeat="smartphone in smartphones | filter: search "> 


 $scope.search = function(item){
    if (!$scope.query || (item.brand.toLowerCase().indexOf($scope.query) != -1) || (item.model.toLowerCase().indexOf($scope.query.toLowerCase()) != -1) ){
        return true;
    }
    return false;
 };
Comments