AngularJS如何只发送一次数据(快按)

AngularJS How to send data only one time (quickly press)

我有textarea,如果我按"Enter"按钮,我需要向服务器发送数据,但是如果快速按几次"Enter","addNewCommentFactory.addComment"发送数据几次次。我怎样才能只发送一个请求(如果快速按下按钮几次)。也许,我应该在第二次发送之前使用延迟。例如,如果按下按钮的时间少于 1 秒,并且下一条评论 == 上一条评论 - 做点什么。请帮忙

$scope.sendComment = function(event, press){

  if(event.keyCode === 13 || press){
    
    if ($scope.new_comment && $scope.new_comment.length > 0) {

addNewCommentFactory.addComment($scope.large, $scope.new_comment).then(function(obj){ 
          $scope.new_comment = null;

              $timeout(function () { event.target.blur() }, 10, false);

        });
     
    }
  }
}
  <textarea  placeholder="Type a message here" ng-model="new_comment" ng-keydown="sendComment($event)"></textarea>

只需在处理 addComment 时禁用该按钮即可。

$scope.buttonDisabled = false;
$scope.sendComment = function(event, press){

  if(event.keyCode === 13 || press){

    if ($scope.new_comment && $scope.new_comment.length > 0) {

$scope.buttonDisabled = true;
addNewCommentFactory.addComment($scope.large, $scope.new_comment).then(function(obj){ 
          $scope.new_comment = null;
          $scope.buttonDisabled = false;
              $timeout(function () { event.target.blur() }, 10, false);

        }, function(){ $scope.buttonDisabled=false; });
    }
  }
}

并且在视图中,

<button ng-disabled="buttonDisabled" />

您还可以通过检查重复项为 http 请求创建服务或修饰当前的 $http 服务来全局防止重复请求。

检查这个:http://blog.codebrag.com/post/57412530001/preventing-duplicated-requests-in-angularjs