LT86
LT86

Reputation: 655

Angular JS - how do I filter multiple elements in array?

I've been messing around with Angular.js but I can't seem to resolve this issue,

Take the pen below and try searching the entire name Zoey White - the filter works fine until you start typing 'White'. I'm assuming something in the code isn't picking up a type of 'AND' function which allows you to filter multiple arrays at a time.

Does anyone have any suggestions to solve this?

http://codepen.io/liamtarpey/pen/jDHcB

Upvotes: 1

Views: 815

Answers (1)

aross
aross

Reputation: 5798

Option 1:

Add fullName to users.

$scope.users = [
    { firstName: "Camila", lastName: "Gilson", fullName: "Camila Gilson" },
    { firstName: "Zoey", lastName: "White", fullName: "Zoey White" },
];

Option 2:

Create an custom search function

HTML

<input ng-model="query">
<ul>
  <li ng-repeat="user in users | filter:search" >
    {{user.firstName}} {{user.lastName}}
  </li>
</ul>

Angular Ctrl

function UsersCtrl($scope) {
  // Defina query
  $scope.query = "";
  $scope.users = [
    { firstName: "Camila", lastName: "Gilson" },
    { firstName: "Zoey", lastName: "White" },
  ];

  // Custom search method
  $scope.search = function(user) {
    // Accept everything if query is empty
    if ($scope.query.length <= 0) return true;

    // Store value of query and name as lower case to make it kind of case insensitive
    var query = (""+$scope.query).toLowerCase(),
        fullName = [user.firstName, user.lastName].join(" ").toLowerCase();

    // Return true full name includes the query
    return fullName.indexOf(query) > -1;
  }
}

Upvotes: 2

Related Questions