Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
604 views
in Technique[技术] by (71.8m points)

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

The typeahead example (http://angular-ui.github.io/bootstrap/#/typeahead) mentions it's easy to implement a back end into this autocomplete, but provides no example. What interests me in particular is finding out the currently entered string so that I can send that to the server and send back an already filtered result - I would like to do this optimization server-side and minimize my queries, I don't think returning the whole result set and just excluding non-matching items for display is feasible for an app that has over 200,000 entries in the database.

Should I, in this case, forget about typeahead altogether and implement a custom solution with a dropdown, or is there a way to do this easily?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...