javascript - 如何在angularjs中只发送一个请求而不是多个请求?

标签 javascript angularjs

我有一个演示,其中用户在输入字段中键入任何内容并将请求发送到服务器。目前,无论何时用户键入它都会触发请求。 我只希望触发一个请求。 例如,如果我键入 “abc”,它会触发三个请求。这是否可能是用户不停地键入任何内容,一秒钟停止后我将发出请求。

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

这是我的代码:

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

最佳答案

使用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 秒后发生。等等

关于javascript - 如何在angularjs中只发送一个请求而不是多个请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53146506/

相关文章:

javascript - ASP :hyperlink is not directing to the linked url

javascript - Angular 返回 $$state 对象 - Angular 和 Kinvey

javascript - 由于 TypeError : ngDialog. open 不是 Scope.$scope.discountModalOpen 的函数,无法使用 ngDialog?

javascript - window.location.hostname 不带 .com 或任何其他前缀

javascript - 在 angularJs 中创建指令

javascript - 为什么它总是在 AngularJS 中选择第一个 TD 单元格

javascript - jQuery JSON AJAX 请求不同域

javascript - 多个复选框来回切换

javascript - 如何推送页面而不是覆盖它

javascript - AngularJS - 输入自动对焦与 ng-if 不工作