4

I want to make online search in angularjs, using ng-keyup function. But I suppose that it is wrong to make query to BD on each keyup. So how can I set timer that will make $http service work only if in last 3 second there were no keyups?

<input type="text" ng-keyup="search(param.values, param.url)">

JS:

app.controller('searchCtrl', function($scope,$rootScope,$http){
$scope.search = function( values , type) {
    var data={};
    data.values=values;
    data.type=type;
    console.log(data);
    $http.post("search.php", data).then(function success (response) {
            console.log(response.data);
            $rootScope.search_result=response.data;
        },function error (response){
            console.log(response.data);
        }
    );
};
});
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
kliukovking
  • 569
  • 1
  • 5
  • 16

2 Answers2

2

You could use ng-model-options to debounce your input value which will tell angular to update ng-model to update after a particular amount of time. Then switch to ng-change event would make more sense instead of ng-keyup. In short, we use debounce to delay our API call.

<input type="text" ng-model="value" ng-change="search(param.values, param.url)" 
  ng-model-options="{ debounce: 3000 }"
Gaurav joshi
  • 1,743
  • 1
  • 14
  • 28
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
1

Waiting for a few seconds in a search module is not very ergonomic / user friendly.

What we usually do is cancel the previous request each time a new character is entered by the user.

You can do this by passing a promise to the timeout property of you $http request.

$http.get(request, {timeout: promise}).then...

You initialise the promise at the start of your search function:

abort = $q.defer();

This way, each time the function is called, you can check if there's a promise and resolve it (cancel it) before making a new request.

if(abort) {
  abort.resolve();
}

Check out the working plunker. (and open the console to see requests being cancelled as you type.)

gyc
  • 4,300
  • 5
  • 32
  • 54
  • Can you write more detailed plz?) I'm not strong in angularjs at all. What for $q service in working plunker? – kliukovking Jun 19 '17 at 10:03
  • @RoGGeR for promises I can only redirect you to https://docs.angularjs.org/api/ng/service/$q It's too vas a subject to explain here. – gyc Jun 19 '17 at 12:07
  • I thought $q is your own service. Link is more than enough, thanks! :) – kliukovking Jun 19 '17 at 13:26