Prevent double POST in angularjs
A directive to handle button blocking until long running operation is completed.
by miensol
HTML
<div ng-app="myApp" ng-controller="ActionController">
<button ng-click="runRegular()" ng-disabled="cantRun">Regular way - Long runnning action</button>
<button bi-click="runPromise()">Method returns promise</button>
<button bi-click="runRegular()">Method doesn't return promise</button>
<div>
<textarea ng-model="response"></textarea>
</div>
</div>
JavaScript
var myApp = angular.module('myApp', []);
myApp.directive('biClick', function ($parse) {
return {
compile: function ($element, attr) {
var handler = $parse(attr.biClick);
return function (scope, element, attr) {
element.on('click', function (event) {
scope.$apply(function () {
var promise = handler(scope, {$event: event});
if (promise && angular.isFunction(promise.finally)) {
element.attr('disabled', true);
promise.finally(function () {
element.attr('disabled', false);
});
}
});
});
};
}
};
});
myApp.controller('ActionController', function ($scope, $http) {
$scope.response = '';
$scope.runRegular = function () {
$scope.cantRun = true;
makePostRequest($http).success(function (data) {
$scope.response += JSON.stringify(data);
}).finally(function () {
$scope.cantRun = false;
});
};
$scope.runPromise = function () {
return makePostRequest($http).success(function (data) {
$scope.response += JSON.stringify(data);
});
};
});
function makePostRequest($http) {
return $http({
method: 'POST',
url: '/echo/json/',
data: "delay=2&json=%7B%22howLong%22%3A%22we+will+see%22%7D",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
};