[英]how to send only one request instead of multiple request in angularjs?
I have a demo in which user type anything in input field and request goes to server.我有一个演示,其中用户在输入字段中输入任何内容并将请求发送到服务器。 Currently whenever user type it fire the request.
当前,每当用户键入它都会触发请求。 I want only one request will fire.
我只想触发一个请求。 Example if i type
"abc"
it fire three request.例如,如果我输入
"abc"
它会触发三个请求。 Is this possible user type anything without stop, after one sec stop I will fire a request.这是否可能是用户不停地输入任何内容,一秒钟后我将发出请求。
i know Inputs can be debounced with the ng-model-options directive: but it fire after time given, but i want user type as long as without stop ,but fire request after stop我知道输入可以用 ng-model-options 指令去抖动:但它会在给定的时间后触发,但我希望用户输入只要不停止,但在停止后触发请求
Here is my code:这是我的代码:
http://plnkr.co/edit/npiA2abAo5SEQFMMpKZO?p=preview http://plnkr.co/edit/npiA2abAo5SEQFMMpKZO?p=preview
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope,$http) {
$scope.name = 'World';
$scope.keyupevt = function(){
console.log('xx')
$http.get("data.json")
.then(function(response) {
console.log(response)
});
}
});
Implement your own debouncing using setTimeout
/ clearTimeout
, something like this will do:使用
setTimeout
/ clearTimeout
实现您自己的去抖动,如下所示:
app.controller('MainCtrl', function($scope,$http) {
$scope.name = 'World';
var timeout = null; // the timeout handle
$scope.keyupevt = function() {
clearTimeout(timeout); // clear any previous timeout (if null, nothing will happen)
timeout = setTimeout(function() { // set a new timeout
console.log('xx'); // that will make the request after 1 second
$http.get("data.json")
.then(function(response) {
console.log(response);
});
timeout = null; // reset timeout (not really necessary but it won't do any harm)
}, 1000); // the code inside will be called after exactly 1000 ms
}
});
Every time a key is down, a request will be set to happen after 1 second from that keydown event.每次按下按键时,都会在该按键按下事件后 1 秒后触发一个请求。 And if the previous request didn't happen yet, the request will be cancelled and a new one will be set to happen after 1 second.
如果前一个请求还没有发生,该请求将被取消,并在 1 秒后设置一个新的请求发生。 etc
等等
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.