防止提交时默认:- Angularjs [英] prevent default on submit :- Angularjs
问题描述
如果填写表单时电子邮件为空,我想防止 http-post 的默认操作为/signUp".
I want to prevent-default action of http-post to '/signUp' if e-mail is null upon filling form.
控制器代码:-
$scope.signUp = function() {
if($scope.email = null);
preventdefault;
}
html(玉石):-
form(name="input", action="/signUp", method="post")
input(type="submit", value="submit")
推荐答案
当你为表单指定了 action 属性时,angularjs 不会做 preventDefault.如果您删除它并添加 ng-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>
在这种情况下,表单将始终具有 preventDefault 并在提交时调用您的 $scope.signUp() 函数,您可以在其中继续向后端/signup 发送 ajax 帖子或进一步验证.请注意,通过在您的输入上使用正确的验证属性(例如 type="email" 和 required),angularjs 将为您执行一些基本验证.您可以在提交按钮上添加一个额外的 ng-disabled="!myForm.$valid"
以在未正确输入电子邮件时保持按钮禁用.
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.
通过在输入上使用 ng-model 就像在我的例子中一样,您的范围将获得一个 $scope.newSignup
对象,您可以检查您的 signUp() 函数以进行进一步验证:
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
}
...
}
这篇关于防止提交时默认:- Angularjs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!