0

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...
}
bobtta
  • 75
  • 1
  • 4
  • http://stackoverflow.com/questions/22158063/angular-ngchange-variant-when-user-finishes-typing – imbond Nov 11 '16 at 07:52
  • @bobtta based on your requirement you can limit. 1. If your search is based on each characters which user typed means then http call should happen 2. Otherwise count the length of the data and call the service by setting some limit – Pitchiah Natarajan Nov 11 '16 at 07:53

2 Answers2

1

There is a debounce option for ng-model for this purpose.

Just add ng-model-options="{ debounce: 1000 }" in your input will do.

Icycool
  • 7,099
  • 1
  • 25
  • 33
  • this work as what i am expecting. coz the answer of @aruna it just let my app wait for 1 sec but still it will query every characters. But with your solution, will just query after 1 second the user pause from typing. It saves me tons of requests to my server. thanks! – bobtta Nov 11 '16 at 12:55
0

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);
};
Aruna
  • 11,959
  • 3
  • 28
  • 42