简体   繁体   English

避免在AngularJS中多次单击按钮

[英]Avoid multiple clicks on button in AngularJS

I have a button which on click will save the form information. 我有一个按钮,单击后将保存表单信息。 The problem is, user instead of clicking 1's on the "Save" button clicks on it multiple times as long as it disappears on the screen. 问题是,用户无需单击“保存”按钮上的1,只要它在屏幕上消失,就可以多次单击它。 With this, I am saving same form which inturn throw duplicate exceptions. 这样,我保存了相同的表格,该表格又引发了重复的异常。 Please help me. 请帮我。 Thanks in advance. 提前致谢。

<button ng-click="myFunc()">Save</button>

In above code, myFunc() is triggered with the number of times user clicks. 在上面的代码中,myFunc()由用户单击的次数触发。

Use a $scope variable and ng-disabled to update the click and check for the variable, 使用$scope变量并ng-disabled以更新点击并检查变量,

<button  ng-click="myFunc()" ng-disabled="buttonClicked"></button>

Controller 控制者

$scope.buttonClicked = true;

我认为在首次单击后禁用该按钮将帮助您解决此问题。

That's in case you want this feature related to multiple buttons: 如果您希望此功能与多个按钮相关:

JS: JS:

$scope.disabled = {};
$scope.myFunc = function(identifier) {
    $scope.disabled[identifier] = 1;
    ...
}

HTML: HTML:

<button  ng-click="myFunc(identifier)" ng-disabled="disabled.identifier"></button>

In case that you want this feature only on one button: 如果您只想通过一个按钮使用此功能:

JS: JS:

$scope.disabled = 0;
$scope.myFunc = function() {
    $scope.disabled = 1;
    ...
}

HTML 的HTML

<button  ng-click="myFunc()" ng-disabled="disabled"></button>

You can disable your submit button after the first click to prevent duplicate entry. 您可以在第一次单击后禁用提交按钮,以防止重复输入。 For Example, you have HTML something like, 例如,您有类似HTML的内容,

 <div ng-app="mydemo" ng-controller="myController">
        <button type="submit" ng-disabled="isDisabled" ng-click="myFunc()"> Submit</button>
    </div>

angular.module('mydemo', [])
    .controller('myController',function($scope){

    $scope.isDisabled = false;

    $scope.disableButton = function() {
        $scope.isDisabled = true; // To disable Button
    }

    });

This way you can disable button. 这样您可以禁用按钮。 It will surely work for you. 它一定会为您工作。 Thanks. 谢谢。

create a directive for this, so that it can be reused 为此创建一个指令,以便可以重复使用

app.directive('clickAndDisable', function() {
  return {
    scope: {
      clickAndDisable: '&'
    },
    link: function(scope, iElement, iAttrs) {
      iElement.bind('click', function() {
        iElement.prop('disabled',true);
        scope.clickAndDisable().finally(function() {
          iElement.prop('disabled',false);
        })
      });
    }
  };
});

so use click-and-disable="myFunc()" rather than ng-click 因此请使用click-and-disable="myFunc()"而不是ng-click

首次单击后隐藏表格可解决此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM