Advanced live-search with AngularJS
04 February 2014
For people familar with AngularJS, it's almost frighteningly easy to make a live-search on a repeating iterator.
Here's such an example: http://jsfiddle.net/r26xm/1/
Out of the box it just works. If nothing is typed into the search field it returns everything.
A big problem with this is that the pattern matching isn't very good. For example, if you search for
ter you get
More realistically you want it to only match with a leading word delimiter. In other words, if you type
ter you want it only to match
Teresa but not
Peter doesn't start with
So, to remedy that we construct a regular expression on the fly with a leading word delimiter. I.e.
Here's an example of that: http://jsfiddle.net/f4Zkm/2/
Now, there's a problem. For every item in the list the regular expression needs to be created and compiled which, when the list is very long, can become incredibly slow.
To remedy that we use
$scope.$watch to create a local regular expression which only happens once per update to
Here's an example of that: http://jsfiddle.net/f4Zkm/4/
That, I think, is a really good pattern. Unfortunately we've left the simplicity but we now have something snappier.
Unfortunately the example is a little bit contrived because the list of names it filters on is so small but the list could be huge. It could also be that we want to make a more advanced regular expression. For example, you might want to allow multiple words to match so as
ter ma should match
John Mayor and
Maria Connor. Then you could make a regular expression with something like
For seasoned Angularnauts this is trivial stuff but it really helped me make an app much faster and smoother. I hope it helps someones else doing something similar.