Marc Rasmussen
Marc Rasmussen

Reputation: 20555

Angular search for combined key

Say you have the following object:

var user: {firstname: 'Marc', lastname:'Ras', age:30};

You have alot of these objects in an array called: user_array

Now you wish to display them in a table so you create your table:

<table>
  <thead>
    <th>Full name</th>
    <th>Age</th>
  </thead>
  <tbody>
    <tr ng-repeat="user in user_array">
      <td>{{user.firstname + ' '+user.lastname}}</td>
      <td>{{user.age}}</td>
    </tr>
  </tbody>
</table>

Now you wish to create an input field where you can search for a user's full name:

And here is kinda ends for me :S how is it possible to search for a combinded key? normally you would have:

<input type="text" ng-model="search.fieldname" />

However you cant do that here since the field is combined of two fieldnames?

Upvotes: 0

Views: 73

Answers (1)

NTP
NTP

Reputation: 4448

add this to your controller

 $scope.filterNameLastName = function (user) {
          var fullname = user.firstname + ' '+ user.lastname;
          if(fullname == $scope.searchParamater)
             return true;
          else
             return false;
        };

and add filter to ng-repeat

<table>
  <thead>
    <th>Full name</th>
    <th>Age</th>
  </thead>
  <tbody>
    <tr ng-repeat="user in user_array | filter:filterNameLastName ">
      <td>{{user.firstname + ' '+user.lastname}}</td>
      <td>{{user.age}}</td>
    </tr>
  </tbody>
</table>

This should give you an idea on how custom filters work. I haven't tested the code so you may have to do some modifications.

Upvotes: 1

Related Questions