在提交prevent默认: - Angularjs [英] prevent default on submit :- Angularjs

查看:138
本文介绍了在提交prevent默认: - Angularjs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要HTTP-POST到'/注册如果邮件是在填写表格为null prevent默认动作。

控制器code: -

  $ scope.signUp =功能(){  如果($ scope.email = NULL);
    preventdefault;}

HTML(玉): -

 形式(NAME =输入,行动=/注册的方法=邮报)
  输入(类型=提交,值=提交)


解决方案

当你有一个表单指定action属性,angularjs不会做preventDefault。
如果你删除它,并添加代替NG-提交:

 <形式NAME =myForm会的方法=后NG提交=注册(myForm会)的novalidate>
    <输入类型=电子邮件NAME =电子邮件NG模型=newSignup.email要求>
    <按钮式=提交>登录UP< /按钮>
< /表及GT;

在这种情况下,表格将始终有preventDefault并提交您的$ scope.signUp()函数将被调用,您可以用AJAX后到后端/注册或进一步验证进行。
请注意,使用适当的验证您输入的属性(如TYPE =电子邮件和需要),angularjs将执行一些基本验证你。
你可以有一个额外的 NG-禁用=!myForm会。$有效的上,而电子邮件是不正确输入提交按钮保持禁用按钮。

通过使用像在我的例子输入NG-型号,范围将得到一个 $ scope.newSignup 对象,你可以在你注册检查()函数进一步验证:

  $ scope.signUp =功能(的HtmlForm){
    如果($ scope.newSignup.email!=='some@email.com'){
       返回false; //你应该表现出一些信息给用户
    }
    ...
}

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

解决方案

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 !== 'some@email.com') {
       return false;  // you should really show some info to the user
    }
    ...
}

这篇关于在提交prevent默认: - Angularjs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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