表格 – ng-submit不会阻止提交

前端之家收集整理的这篇文章主要介绍了表格 – ng-submit不会阻止提交前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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>

有没有人对我在这里做错了什么有建议?

解决方法

您可以使用内置属性$valid:

<form name="testForm" novalidate ng-submit="testForm.$valid && submit()">

仅当testForm.$valid为true时才调用submit函数.

我在本教程中学到了它:https://www.codeschool.com/courses/shaping-up-with-angular-js.

猜你在找的Angularjs相关文章