简体   繁体   中英

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. 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.

Use a $scope variable and ng-disabled to update the click and check for the variable,

<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:

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

HTML:

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

In case that you want this feature only on one button:

JS:

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

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,

 <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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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