How do you disable the submit button after a single click to prevent multiple submissions in Angularjs?
You were very close to the answer. The only thing you missed out was calling the someFunc()
function on button using ng-click
.
The other issue is, in your controller the function should be $scope.someFunc()
and not var someFunc()
Working example: Your index.html should be like:
<html>
<head>
<script data-require="[email protected]" data-semver="1.3.15" src="https://code.angularjs.org/1.3.15/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
<script src="application.js"></script>
</head>
<body ng-app="demo" ng-controller="demoController">
<button type="submit" ng-disabled="isDisabled" ng-click="disableButton()"> Click me to disable myself</button>
</body>
</html>
And your controller application.js be like:
angular.module('demo', [])
.controller('demoController',function($scope){
$scope.isDisabled = false;
$scope.disableButton = function() {
$scope.isDisabled = true;
}
});
Another way is to write a directive which disables the submit button
angular.module('myApp').directive('clickedDisable', function(){
return {
restrict: 'A',
link: function(scope, ele, attrs){
$(ele).click(function(){
$(ele).attr('disabled', true);
});
}
};
And in the HTML
<button type="submit" clicked-disable></button>
I didn't like any of the provided answers as they all clutter the global scope with the isDisabled
variable, why not do it this way instead?
<button type="submit" ng-click="disableButton($event)">Submit</button>
.
$scope.disableButton = function($event) {
$event.currentTarget.disabled = true;
};
if if you need to submit a form before the disable.
this code is not tested
<form ng-submit="disableFormSubmitButton($event)">
<button type="submit">Submit</button>
</form>
.
$scope.disableFormSubmitButton = function($event) {
$($event).find('[type=submit]').prop('disabled',true);
};