Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter on multiple fields in AngularJS ng-repeat

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>
like image 821
mofitty Avatar asked May 12 '26 17:05

mofitty


1 Answers

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.

like image 191
Andy Rheingans Avatar answered May 15 '26 12:05

Andy Rheingans



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!