在SO上有很多类似的问题。我经历了很多,但没有发现我的问题。
我有一个使用ng-submit
的表单。不幸的是,即使表单无效,按Enter或单击提交仍然有效。调用ng-submit
方法。
CodePen示例:http://codepen.io/calendee/pen/tgFhq
<form name="testForm" novalidate ng-submit="submit()">
<label for="firstname">First Name:</label>
<input type="text" name="firstname" ng-model="data.firstname" required="true" ng-minlength="4" ng-maxlength="10">
<div class="errors">
<p>firstname Errors:</p>
<p ng-show="testForm.firstname.$error.required">firstname is required</p>
<p ng-show="testForm.firstname.$error.minlength">firstname is too short</p>
<p ng-show="testForm.firstname.$error.maxlength">firstname is too long</p>
</div>
<label for="lastname">Last Name:</label>
<input type="text" name="lastname" ng-model="data.lastname" ng-required="true" ng-minlength="4" ng-maxlength="10">
<div class="errors">
<p>lastname Errors:</p>
<p ng-show="testForm.lastname.$error.required">lastname is required</p>
<p ng-show="testForm.lastname.$error.minlength">lastname is too short</p>
<p ng-show="testForm.lastname.$error.maxlength">lastname is too long</p>
</div>
<button class="button button-balanced" type="submit">Submit</button>
</form>
如果我更改表单ng-form
,即使表单有效,提交事件也不起作用。
CodePen示例:http://codepen.io/calendee/pen/imJdc
<ng-form name="testForm" novalidate ng-submit="submit()">
<label for="firstname">First Name:</label>
<input type="text" name="firstname" ng-model="data.firstname" required="true" ng-minlength="4" ng-maxlength="10">
<div class="errors">
<p>firstname Errors:</p>
<p ng-show="testForm.firstname.$error.required">firstname is required</p>
<p ng-show="testForm.firstname.$error.minlength">firstname is too short</p>
<p ng-show="testForm.firstname.$error.maxlength">firstname is too long</p>
</div>
<label for="lastname">Last Name:</label>
<input type="text" name="lastname" ng-model="data.lastname" ng-required="true" ng-minlength="4" ng-maxlength="10">
<div class="errors">
<p>lastname Errors:</p>
<p ng-show="testForm.lastname.$error.required">lastname is required</p>
<p ng-show="testForm.lastname.$error.minlength">lastname is too short</p>
<p ng-show="testForm.lastname.$error.maxlength">lastname is too long</p>
</div>
<button class="button button-balanced" type="submit">Submit</button>
</ng-form>
有人对我在这里做错了什么有建议吗?
答案 0 :(得分:7)
您可以使用内置属性$valid
:
<form name="testForm" novalidate ng-submit="testForm.$valid && submit()">
仅当testForm.$valid
为真时才会调用提交函数。
我在本教程中学到了它:https://www.codeschool.com/courses/shaping-up-with-angular-js。
答案 1 :(得分:1)
使用ng-submit
时,表单不会直接提交给服务器。在submit()
方法中,您可以决定是将表单信息提交给服务器还是拒绝提交。检查表单输入控件的有效性,然后将信息发送到服务器端。