I have a form I'd like to deliver via AJAX :
<form class="form-inline ng-pristine" ng-submit="sendForm()" method="post" action="/sign_up" accept-charset="UTF-8"> $scope.sendForm = (e) -> e.preventDefault -> console.log 'sendForm()' return false
The console.log
appears, and immediately it delivers the form.
It ignores both the e.preventDefault()
, and the return false
.
AngularJS reminds me of the honey badger. It just doesn't care.
Definition and Usage. 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.
The preventDefault() method of the Event interface tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be.
To prevent a default action – use either event. preventDefault() or return false .
I know I am pretty late to the party, but in case you did not figure it out yet, you can keep the action and make sure the form is not actually submitted by passing $event
to the ng-submit
function. Then you can use event.preventDefault();
in your controller after you do all your processing.
So in your case it would be:
<form class="form-inline ng-pristine" ng-submit="sendForm($event)" method="post" action="/sign_up" accept-charset="UTF-8"> $scope.sendForm = (e) -> // doing stuff e.preventDefault()
Hope this helps.
Well, you're not doing it the "Angular way". Angular provides a directive called ng-submit, which does that preventDefault for you (as long as you don't have an action attribute specified on your form).
Markup (with validation!)
<form name="myForm" ng-submit="sendForm()"> <div> <input type="text" name="name" ng-model="data.name" required/> <span ng-show="myForm.name.$error.required && myForm.name.$dirty">required</span> </div> <div> <input type="email" name="email" ng-model="data.email" required/> <span ng-show="myForm.name.$error.required && myForm.name.$dirty">required</span> <span ng-show="myForm.name.$error.email && myForm.name.$dirty">invalid email</span> </div> <button type="submit" ng-disabled="myForm.$invalid">Submit</button> </form>
Code
app.controller("MyCtrl", function($scope, $http) { $scope.sendForm = function (){ $http.post('/Submit/To/Url', $scope.data).success(function(data) { alert('done!'); }); }; });
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