Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter ng-repeat based on search input

I have the following html:

  <div>
    <div>
      <input type="text" placeholder="Search" ng-model="userSearch.firstname">
    </div>
  </div>

 <div>
   <div ng-repeat="user in users | filter:userSearch ">
     <div>
       {{user.firstname}} {{user.lastname}}
     </div>
   </div>
 </div>

So I have an input field where the users can type and search in my list of all users. Is there a way I can apply a filter inline in the ng-repeat based on what the user types in the search input?

Current solution only filters on firstname

I would like to filter on both first and last name

Tried:

  <div>
    <div>
      <input type="text" placeholder="Search" ng-model="userSearch">
    </div>
  </div>

 <div>
   <div ng-repeat="user in users | filter:{firstname: userSearch, lastname: userSearch} ">
     <div>
       {{user.firstname}} {{user.lastname}}
     </div>
   </div>
 </div>

But I think that is an AND not an or.

like image 231
lostintranslation Avatar asked Jan 22 '15 02:01

lostintranslation


People also ask

How do I filter data in ng-repeat?

The ng-repeat values can be filtered according to the ng-model in AngularJS by using the value of the input field as an expression in a filter. We can set the ng-model directive on an input field to filter ng-repeat values.

How do I get the index of an element in NG-repeat?

Note: The $index variable is used to get the Index of the Row created by ng-repeat directive. Each row of the HTML Table consists of a Button which has been assigned ng-click directive. The $index variable is passed as parameter to the GetRowIndex function.

Can we use filter in NG-model?

By setting the ng-model directive on an input field, we can use the value of the input field as an expression in a filter.


1 Answers

Change ng-model from userSearch.firstname to just userSearch.

 <input type="text" placeholder="Search" ng-model="userSearch">

http://jsbin.com/keyuno/1/edit?html,js,output

Alternatively you could change filter:userSearch to filter:userSearch.firstname. You just need to be sure the filter matches the model.

like image 132
Aweary Avatar answered Sep 26 '22 00:09

Aweary