I need to enable/disable a button after click with Angular. When a user clicks "Submit form", it makes an http
request. If an error occurs (inside the catch
), I want to re-enable the directive button so that a user can try again. I have a directive with controllerAs
syntax and isolateScope
. Below is the code I have (simplified for here);
myCtrl
parent controller (controllerAs is myCtrl
)
vm.submit = function() {
MyService
.update()
.then(function(res) {
// success
})
.catch(function(err) {
vm.error = true;
// error
});
};
Parent view with my-form
directive
<my-form form-submit='myCtrl.submit()'></my-form>
myForm
Directive
function myForm() {
return {
restrict: 'E',
replace: true,
templateUrl: 'myform.html',
scope: {
formSubmit: '&',
},
require: ['form', 'myForm'],
link: function(scope, element, attrs, ctrls) {
var formCtrl = ctrls[0];
var directiveCtrl = ctrls[1];
scope.isButtonDisabled = false;
scope.submit = function() {
scope.submitted = true;
directiveCtrl.submit();
};
},
controller: function($scope, $element, $attrs) {
var vm = this;
// Submit parent function
vm.submit = function() {
vm.formSubmit();
};
},
controllerAs: 'myFormCtrl',
bindToController: true
};
}
angular.module('mymodule')
.directive('myForm', [ myForm ]);
myForm
directive template
<form name='myForm' novalidate>
// form fields
<button ng-click='submit()' ng-disabled='isButtonDisabled'>Submit Form</button>
</form>