3

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>

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.