Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prevent default on submit :- Angularjs

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")
like image 525
Sangram Singh Avatar asked Oct 28 '13 14:10

Sangram Singh


People also ask

How do I stop submit by default?

The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur. For example, this can be useful when: Clicking on a "Submit" button, prevent it from submitting a form. Clicking on a link, prevent the link from following the URL.

What is preventDefault in AngularJS?

See, the event.preventDefault is a javascript function and is independent of angular version. However the binding used for (ngSubmit) in angularjs will change but the event.preventdefault would remain the same.

How do I disable e preventDefault?

Calling preventDefault() during any stage of event flow cancels the event, meaning that any default action normally taken by the implementation as a result of the event will not occur. You can use Event. cancelable to check if the event is cancelable. Calling preventDefault() for a non-cancelable event has no effect.

What is Ng submit in AngularJS?

AngularJS ng-submit Directive The ng-submit directive specifies a function to run when the form is submitted. If the form does not have an action ng-submit will prevent the form from being submitted.


1 Answers

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
    }
    ...
}
like image 54
Dan Caragea Avatar answered Sep 21 '22 05:09

Dan Caragea