How to tie angular-ui’s typeahead with a server via $http for server side optimization?

There is a way to implement this very easily, no need to roll out your custom solution (at least not for this case!). Basically you can use any function as part of the typeaheads expression, ex.:

<input type="text" ng-model="selected" typeahead="state for state in getStates($viewValue)">

As you can see from this example the getStates($viewValue) method (defined on a scope) can be called and the $viewValue corresponds to a value entered by a user.

What is the best here is that your function can return a promise and this promise will be correctly recognized by the typeahead.

Some time ago I’ve written a sample plunk that shows how to use server-side calls to provide auto-complete. Check this plunk that shows autocomplete for all the cities in US (based on geobytes.com), where cities are queried live from a JSONP service:

http://plnkr.co/edit/t1neIS?p=preview

Check it out for a working example on how to do filtering on the server side (you need to type at least 3 characters to see results). Of course you are not limited to jsonp calls, you can use any method returning a promise.

Leave a Comment