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);
}
);
};
});
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 }"
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.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.