Swayam Siddha
Swayam Siddha

Reputation: 245

Angular JS - ng-repeat filter object array based on multiple object properties using the same ng-model

I have an array of employees that look like

$scope.Arr = [
           {'name':'John','title':'CEO','Age':'32'}, 
           {'name':'Jill', 'title':'Sales Executive', 'Age':'44'},
           {'name':'Alex','title':'Developer','Age':24}
          ];

I use ng-repeat to render this array in html and am looking to make the filter work such that the same input control's value can be used to filter employees based on both the name as well as title.

<input type='text' data-ng-model='search.name' />

<div>
  <span data-ng-repeat="emp in Arr | filter:search">
  <p> {{emp.name}} </p>
  <p> {{emp.title}} </p>
  </span>
</div>

The above code only lets me filter on basis of employee name

Upvotes: 2

Views: 934

Answers (1)

akashrajkn
akashrajkn

Reputation: 2315

You can use filter to search based on both name and title.

The default angularjs filter on the expression "emp in Arr | filter: {name: $select.search, title: $select.search}" performs an AND between "name: $select.search" and "title: $select.search"

Write a custom filter to perform OR operation

var app = angular.module('myApp', []);

app.filter('customFilter', function() {
    return function(names, title) {
        var output = [];

        if(angular.isArray(names)) {
            names.forEach(function(item) {
                var nameMatch = false;

                var keys = Object.keys(title);
                for(var i=0; i<keys.length; ++i) {
                    var t = keys[i];
                    var text = title[t].toLowerCase();
                    if(item[t].toString().toLowerCase().indexOf(text) !== -1) {
                        nameMatch = true;
                        break;
                    }
                }

                if(nameMatch) {
                    output.push(item);
                }
             });
          }
          else {
              output = names;
       }

       return output;
   };
});

Basically, this code lets you filter based on both name and title. Hope this helps.

Upvotes: 2

Related Questions