How to filter on multiple fields in AngularJS ng-repeat

11,077

According to the angular docs it looks like you can pass in an object to the filter. So you could do something like:

scope.query = {};

Then in your html

First name: <input ng-model="query.firstName" />
Last name: <input ng-model="query.lastName" />

And your filter expression would remain the same:

ng-repeat="reservation in reservations | filter:query"

See the details for the 'expression' argument for more info: https://docs.angularjs.org/api/ng/filter/filter.

Share:
11,077
mofitty
Author by

mofitty

Updated on June 04, 2022

Comments

  • mofitty
    mofitty almost 2 years

    I am creating a site with a search using the query filter in AngularJS. I have found many tutorials on how to implement this search in one field, but none that explain how to search across multiple fields. So if your data has firstName: "John", lastName: "Smith" I would like to be able to enter "John Smith" in my search bar, and find the correct results, but only the exact text of "John" or "Smith" works.

    <div ng-include="'partials/navbar.html'"></div>
    <div class="container" ng-controller="ResListCtrl">
        <div class="row">
            <div class="col-md-2">
                Search: <input ng-model="query">
            </div>
        </div>
        <hr>
        <div class="row">
            <div class="col-md-10">
                <ul ng-repeat="reservation in reservations | filter:query">
                    <li><a href="#">{{reservation.firstName}} {{reservation.lastName}}</a></li>
                    <p>{{reservation.resort}}</p>
                </ul>
            </div>
        </div>
    </div>
    
  • mofitty
    mofitty over 9 years
    Sorry, I guess I didn't make my question clear. I want to be able to search both first and last name in the same search bar. This solution makes two separate search bars.
  • Admin
    Admin over 9 years
    You could set up a $watch on that search input, then use split(' ') to get first and last name, and then use the results from that to populate the query.