bobtta bobtta - 27 days ago 7
AngularJS Question

send data after pause in ng-keyup (Angularjs)

I use ng-keyup to my angular app for searching data to my backend. But the problem is, it will send request to my server every press. How can I make it send post request to my backend after the user pause/stop typing? Or it's wrong to use ng-keyup for this?

my html

<input ng-keyup="search(data)" ng-model="data" type="text"/>


controller

$scope.search=function($scope, $http){
....http post codes here...
}

Answer

You can use ng-change with $timeout as below.

Note: $http and $timeout should be injected in your controller since you used $http as parameter in your search method above.

<input ng-change="search(data)" ng-model="data" type="text"/>

JS

var handle;
$scope.search = function(data){
   if(handle){
        $timeout.cancel(handle);
        handle  = null;
    }
    handle = $timeout(function(){
       // $http.post(..)
    }, 1000);
};