angularjsinput-filtering

How to filter data in AngularJS


I'm trying to implement a simple search textfield. I want it to display contacts by filtering their name and phone number. It seems like whenever I type in a letter , it shows me all of the contacts' names that have that letter in their name, but it also searches the other attributes of each contact (address, city, mail, etc), so if a contact's name does not contain the letter, it's still shown becuase its other attributes contain it. Obviously that is not what I am trying to implement.

I want it to be able to filter contacts by both name and phone number.

<input type="text" ng-model="query" placeholder="search"/>
<div ng-repeat="c in contacts|filter: query"> ...<\div>

How can I solve this problem? Thanks for helping


Solution

  • It's simple to filter based on one field: just change your filter to | filter:{name: query}

    It's simple to filter based on two fields if they both have to match: just change your filter to | filter:{name: query, phoneNumber: query}.

    It's harder to filter based on two fields if you want either to match. Here's someone who had the same question. The first response has a simple hack to make things work if you're just playing around, but if you have more data you'll want to work through this blog post.

    By the way, your question was likely downvoted because this isn't too hard to Google. Searching [angularjs filter by field] got me partway there, and then [ng-repeat filter multiple fields] took me to the results I've linked above.