Angular JS does not allow preventDefault or return false to work on form submission

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.

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!');
       });
    };
});

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.

You can get the event by passing $event into your ng-click or ng-submit. It's like dependency injection, except in your expressions.

html

<form class="form-inline ng-pristine" ng-submit="sendForm($event)" method="post" action="/sign_up" accept-charset="UTF-8">

coffeescript

$scope.sendForm = (e) ->
  e.preventDefault()
  console.log 'sendForm()'
  false  

Other way to solve this is with a directives.

app.directive("submit", [function () {
    return {
        scope: {
            submit: "="
        },
        link: function (scope, element, attributes) {
            element.bind("submit", function (loadEvent) {
                return scope.submit(loadEvent);
            });
        }
    }
}]);

<form submit="sendForm" method="post" action="/sign_up">

$scope.sendForm = function(e) {
  if ($scope.whatever)
      return true;
  else
      return false;
};