Search code examples
javascriptangularjshttpkeyup

searching query to mysql in angularjs using ng-keyup but $http only after 3 seconds


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);
        }
    );
};
});

Solution

  • 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 }"