Alex Wohlbruck
Alex Wohlbruck

Reputation: 1436

Angular Filter - Search two concatenated fields

I have a list of people whose model has first and last name properties. Using angular's filter functionality, I can create a basic search that filters the list down. However at it's basic form, a user can't search both a first and last name to get any results, because angular only looks at one property at a time. Is there a way to create 'virtual' properties that concatenate two others to use for search?

If I explained that terribly, which I usually do, just try searching 'Steve Jobs' in this snippet:

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

app.controller('myCtrl', function($scope) {
  $scope.people = [
    {first: 'John', last: 'Smith'},
    {first: 'Jane', last: 'Doe'},
    {first: 'Bill', last: 'Gates'},
    {first: 'John', last: 'Krasinski'},
    {first: 'Ada', last: 'Lovelace'},
    {first: 'Brad', last: 'Pitt'},
    {first: 'Steve', last: 'Jobs'},
    {first: 'Bill', last: 'Clinton'},
    {first: 'Britishname', last: 'Complicated'},
    {first: 'Steve', last: 'Wozniak'}
  ];
});
<div ng-app="app" ng-controller="myCtrl">
  <input type="text" ng-model="search" placeholder="Search...">
  
  <ul>
    <li ng-repeat="person in people | filter: search">
      {{person.first}} {{person.last}}
    </li>
  </ul>
</div>


<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

Upvotes: 1

Views: 1058

Answers (1)

Alex Wohlbruck
Alex Wohlbruck

Reputation: 1436

Actually, I've figured it out on my own, but I'll leave this here for others. You can create a function for the filter like this:

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

app.controller('myCtrl', function($scope) {
  $scope.people = [
    {first: 'John', last: 'Smith'},
    {first: 'Jane', last: 'Doe'},
    {first: 'Bill', last: 'Gates'},
    {first: 'John', last: 'Krasinski'},
    {first: 'Ada', last: 'Lovelace'},
    {first: 'Brad', last: 'Pitt'},
    {first: 'Steve', last: 'Jobs'},
    {first: 'Bill', last: 'Clinton'},
    {first: 'Britishname', last: 'Complicated'},
    {first: 'Steve', last: 'Wozniak'}
  ];
  
  $scope.criteriaMatch = function(criteria) {
    return function(person) {
      var concatenated = person.first + ' ' + person.last;
      return !criteria || concatenated.toLowerCase().indexOf(criteria.toLowerCase()) !== -1;
    }
  };
});
<div ng-app="app" ng-controller="myCtrl">
  <input type="text" ng-model="search" placeholder="Search...">
  
  <ul>
    <li ng-repeat="person in people | filter: criteriaMatch(search)">
      {{person.first}} {{person.last}}
    </li>
  </ul>
</div>


<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

Upvotes: 0

Related Questions