If I have declared a form with a function tied to the ng-submit
directive, how can I prevent that function from being executed when the submit button is clicked but the form is invalid?
I have found two solutions to this that has big drawbacks and therefore I do not want to use them:
Pass in the form to the controller:
//HTML
<form ng-submit="myFunc($form, model)">
//JavaScript
$scope.myFunc = function($form, model) {
if ($form.$valid) {
//do stuff
}
}
This is bad since it ties the function to being called from a form.
Make the submit button disabled when the form is invalid.
<input type="submit" ng-disabled="!form.$valid"/>
This is bad because disabled elements are hard to work with. Tooltips dont show when the button is hovered or clicked so it is hard to give feedback to a user trying to click the disabled button.
Is there another solution to this problem?
It's possible to do this:
<form name="myForm" ng-submit="myForm.$valid && myFunc()">
But there's not much harm in checking the validity within ngSubmit itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With