2

我有一个演示,其中用户在输入字段中输入任何内容并将请求发送到服务器。目前,只要用户键入它就会触发请求。我只想触发一个请求。例如,如果我键入"abc"它会触发三个请求。这可能是用户不停地输入任何内容吗?停止一秒钟后,我将触发一个请求。

我知道 输入可以使用 ng-model-options 指令去抖动:但它在给定时间后触发,但我希望用户类型只要不停止,但在停止后触发请求

这是我的代码:

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

1 回答 1

1

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

每次按键按下时,请求将设置为在按键按下事件后 1 秒后发生。如果之前的请求还没有发生,则该请求将被取消,并设置一个新的请求在 1 秒后发生。ETC

于 2018-11-04T23:38:51.233 回答