How to filter on multiple fields in AngularJS ng-repeat

I am creating a search site using a request filter in AngularJS. I've found many tutorials on how to implement this search in a single field, but none of them explain how to search across multiple fields. So if your data has firstName: "John", lastName: "Smith", I would like to be able to type "John Smith" into my search bar and find the correct results, but only the exact text "John" or "John", Smith ".

<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>

      

+3


source to share


2 answers


According to the angular docs, it looks like you can pass an object to a filter. Thus, you can 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 will remain the same:

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

      

For details on the 'expression' argument see details: https://docs.angularjs.org/api/ng/filter/filter .

+5


source


The filter also accepts a function ( https://docs.angularjs.org/api/ng/filter/filter ):



function(value, index) {
  return value === query.first_name + ' ' + query.last_name;
}

      

0


source







All Articles