角JS不允许preventDefault或返回false在表单提交工作 [英] Angular JS does not allow preventDefault or return false to work on form submission

查看:178
本文介绍了角JS不允许preventDefault或返回false在表单提交工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表格,我想通过AJAX提供:

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  

将出现的console.log ,并立即将其传递的形式。

The console.log appears, and immediately it delivers the form.

它忽略了两个即preventDefault()返回false

AngularJS提醒蜜獾的我。它只是不小心。

AngularJS reminds me of the honey badger. It just doesn't care.

推荐答案

好了,你不这样做的角路。角提供了一个名为NG提交指令,这是否preventDefault你(只要你没有你的表格上指定的操作属性)

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).

标记(与验证!)

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

这篇关于角JS不允许preventDefault或返回false在表单提交工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆