Preventing / dealing with double button clicks in angular

angularjs

Solution

Using `ng-disabled` worked just fine in this example. No matter how furiously I clicked the console message only populated once.

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.submitData = function() {
    $scope.buttonDisabled = true;
    console.log("button clicked");
  }

  function augment() {
    var name, fn;
    for (name in $scope) {
      fn = $scope[name];
      if (typeof fn === 'function') {
        if (name.indexOf("$") !== -1) {
          $scope[name] = (function(name, fn) {
            var args = arguments;
            return function() {
              console.log("calling " + name);
              console.time(name);
              fn.apply(this, arguments);
              console.timeEnd(name);
            }
          })(name, fn);
        }
      }
    }
  }

  augment();
});
<!doctype html>
<html ng-app="plunker">

<head>
  <meta charset="utf-8">
  <title>AngularJS Plunker</title>
  <link rel="stylesheet" href="style.css">
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.js"></script>
  <script src="app.js"></script>
</head>

<body ng-controller="MainCtrl">
  <input type="button" ng-click="submitData()" ng-disabled="buttonDisabled" value="Submit" />
</body>

</html>

I was curious exactly how long it takes for angular to apply the changes to the `buttonDisabled` flag. If you check the console in the plunker example it displays how long it takes the `$eval` and `$apply` methods to execute. On my machine it took an average of between 1-2 milliseconds.

Problem

In angular we can set up a button to send ajax requests like this in view: ``` ... ng-click="button-click" ``` and in controller: ``` ... $scope.buttonClicked = function() { ... ... // make ajax request ... ... } ``` So to prevent a double submit I could set a flag to buttonclicked = true when a button is click and unset it when the ajax callback is finished. But, even then control is handled back to angular who will updates to the Dom. That means there is a tiny window where the button could be clicked again before the original button click has completely 100% finished. It's a small window but can still happen. Any tips to completely avoid this from happening - client side i.e. without making any updates to server. Thanks

Original source

Related problems