prevent default on submit :- Angularjs
When you have the action attribute specified for the form, angularjs will not do preventDefault. If you remove it and add ng-submit instead:
<form name="myForm" method="post" ng-submit="signUp(myForm)" novalidate>
<input type="email" name="email" ng-model="newSignup.email" required>
<button type="submit">sign up</button>
</form>
In this case the form will always have preventDefault and on submit your $scope.signUp() function will be called where you can proceed with an ajax post to the backend /signup or further validation.
Note that by using proper validation attributes on your inputs (like type="email" and required), angularjs will perform some basic validation for you.
You can have an extra ng-disabled="!myForm.$valid"
on the submit button to keep the button disabled while the email is not correctly entered.
By using ng-model on the inputs like in my example, your scope will get a $scope.newSignup
object which you can check in your signUp() function for further validation:
$scope.signUp = function(htmlForm) {
if ($scope.newSignup.email !== '[email protected]') {
return false; // you should really show some info to the user
}
...
}
Sangram Singh
Making an effort to become a better programmer. Motivated by some startup ideas and the aspiration of making a more vibrant eco-system for developing Startups. I am /sangramfuture on twitter/facebook/quora. Would be happy to get in touch.
Updated on July 13, 2022Comments
-
Sangram Singh almost 2 years
I want to prevent-default action of http-post to '/signUp' if e-mail is null upon filling form.
Controller Code:-
$scope.signUp = function() { if($scope.email = null); preventdefault; }
html (jade) :-
form(name="input", action="/signUp", method="post") input(type="submit", value="submit")
-
berliner over 10 yearsWhat if I need the form to work even if javascript is disabled. Then I would need the action attribute, otherwise the form doesn't submit. How would I prevent angular (in this case with javascript enabled obviously) from submitting?
-
berliner over 10 yearsAh, got it from here groups.google.com/forum/#!topic/angular/pqoaPaLdhR4. Registering my own submit handler will do it.