Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS / Typeahead - Delay call to $scope method

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.

like image 476
Dinesh M Avatar asked Dec 06 '22 06:12

Dinesh M


2 Answers

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

like image 77
pkozlowski.opensource Avatar answered Dec 24 '22 10:12

pkozlowski.opensource


Check AngularStrap solution: https://github.com/mgcrea/angular-strap/blob/master/src/directives/typeahead.js

OR

It can be easily done like this in javascript:

var autocomplete = $('#searchinput').typeahead().on('keyup', delayRequest);

function dataRequest() {
    // api request here
}

function delayRequest(event) {
    if(delayRequest.timeout) {
        clearTimeout(delayRequest.timeout);
    }

    var target = this;

    delayRequest.timeout = setTimeout(function() {
        dataRequest.call(target, event);
    }, 200); // 200ms delay
}
like image 42
EpokK Avatar answered Dec 24 '22 12:12

EpokK