Custom AngularJS search filter

I’m working on an Angular-based Chrome app at the moment and I needed to make a search box. The search filter example in the Angular docs shows how to search based on a single property of the array objects. It also shows the use of multiple input boxes to search in different properties.

The example data has “Julie 555-8765” and “Juliette 555-5678”. Wouldn’t it be nice if the search field could handle queries like “julie 555” and show both of them as search results?


In essence, the search filter would need to match “555” in the “phone” property and “julie” in the “name” property. It would have to break down the search query into parts (“555” and “julie”), make sure that each part matches one of the properties of the object and show it in the results only if all parts are found in the object. This can be done by combining the multiple properties of the object into a single string, checking if each query part is found as a substring of the object string, and doing an AND operation of the results of all query parts.

Here’s some sample code

A Plunker version of the same code is available here

Go ahead and type something like “555” and you’ll see two results, Jane Doe and Jane Smith. If you change that to “555 Doe”, the Jane Smith result is dropped.

Note that the filter function is rather intensive because it converts each object to a JSON string and tries to locate all query string parts in it. To prevent frequent execution of the filter function, this makes use of the relatively new ng-model-options (added in Angular 1.3) to delay the ng-model update by 400 milliseconds. You may want to tweak the delay amount.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s