AngularJS / Typeahead - Delay call to $scope method

Dinesh M picture Dinesh M · Aug 12, 2013 · Viewed 7.5k times · Source

I have following input field code snippet from here I am calling AngularJS $scope method in the following way

<input class="search-txt-input"
       id="partner_name"
       name="partner_name"
       title="Partner Name"
       type="text"
       autocomplete="off"
       ng-model="selectedPartner"
       typeahead="partner as partner.name for partner in retrievePartnerList($viewValue)"
       typeahead-items="2"
       typeahead-min-length="3">

So when I type a minimum of 3 characters in the text field, it will fire an AJAX call to to retrievePartnerList function.

Also my server response is very slow, so for 10 characters 7 Ajax calls comes in queue and after some time I am getting a TimeOutError.

So to solve this I am trying to find a way using which I can delay the call to retrievePartnerList() method, so that less AJAX calls will be sent and it probably reduce the burden to my server.

So I am not sure how I can use setTimeout() function here.

Let me know if any one of you have any idea on this.

Answer

pkozlowski.opensource picture pkozlowski.opensource · Aug 12, 2013

Yes, you can easily delay firing off matching by specifing the typeahead-wait-ms attribute. As the name of the attribute implies, it takes a value in milliseconds and will delay matching , waiting specified number of milliseconds after user stopped typing before firing requests to the server.

Here is a demo showing this in action: http://plnkr.co/edit/fHLqDx?p=preview