how to send only one request instead of multiple request in angularjs?

3653 views javascript
4

I have a demo in which user type anything in input field and request goes to server. Currently whenever user type it fire the request. I want only one request will fire. Example if i type "abc" it fire three request. Is this possible user type anything without stop, after one sec stop I will fire a request.

i know Inputs can be debounced with the ng-model-options directive: but it fire after time given, but i want user type as long as without stop ,but fire request after stop

Here is my code:

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

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope,$http) {
   $scope.name = 'World';


    $scope.keyupevt = function(){
       console.log('xx')
       $http.get("data.json")
            .then(function(response) {
               console.log(response)
            });
    }
});

answered question

you could have it fire if you lose focus and input > 0. You could also have a minimum character limit and wait until you at least hit that before sending a request.

1 Answer

2

Implement your own debouncing using setTimeout/clearTimeout, something like this will do:

app.controller('MainCtrl', function($scope,$http) {
    $scope.name = 'World';

    var timeout = null;                                // the timeout handle
    $scope.keyupevt = function() {
       clearTimeout(timeout);                          // clear any previous timeout (if null, nothing will happen)

       timeout = setTimeout(function() {               // set a new timeout
           console.log('xx');                          // that will make the request after 1 second
           $http.get("data.json")
             .then(function(response) {
               console.log(response);
           });
           timeout = null;                             // reset timeout (not really necessary but it won't do any harm)
       }, 1000);                                       // the code inside will be called after exactly 1000 ms
    }
});

Every time a key is down, a request will be set to happen after 1 second from that keydown event. And if the previous request didn't happen yet, the request will be cancelled and a new one will be set to happen after 1 second. etc

posted this

Have an answer?

JD

Please login first before posting an answer.