3

尝试为我的表单中的复选框添加表单验证器,以防它未选中,表单将具有ng-invalid.

<li class="terms_checkbox"><input type="checkbox" id="checkbox_terms" name="terms" /><label for="checkbox_terms"></label></li>
<li class="accept">I have read and accept the terms and conditions</li>

如果未选中,任何关于什么可以触发添加ng-invalid到表单的建议,反之亦然。

4

2 回答 2

8

您需要做的就是required在复选框上添加属性和 ng-model,以便在表单验证期间进行检查。

<li class="terms_checkbox">
   <input type="checkbox" 
       id="checkbox_terms" name="terms" ng-model="agreement" required />
   <label for="checkbox_terms"></label>
</li>

angular.module('app', []).controller('ctrl', function($scope) {

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  <form name="form" novalidate>
    <ul>
      <li class="terms_checkbox">
        <input type="checkbox" id="checkbox_terms" name="terms" ng-model="agreement" required />
        <label for="checkbox_terms"></label>
      </li>
      <li class="accept">I have read and accept the terms and conditions</li>
      <li>
        <button ng-disabled="form.$invalid">Submit</button>
      </li>
    </ul>
  </form>
</div>

于 2015-01-20T19:22:55.357 回答
1

好吧,对于初学者来说,这不是一种形式。如果你想保持这个结构,你可以简单地在复选框上应用一个模型,并根据 的值有条件地放置一个“无效”属性$scope.checked,如下所示:

<ul>
  <li class="terms_checkbox">
    <input ng-model="checked" type="checkbox" id="checkbox_terms" name="terms" />
    <label for="checkbox_terms"></label>
  </li>
  <li class="accept">I have read and accept the terms and conditions</li>
</ul>

但是,我建议将其包围在实际表单中,并将required属性放在复选框上。这个 :

<form name="myForm">
  <ul>
    <li class="terms_checkbox">
      <input type="checkbox" id="checkbox_terms" name="terms" required />
      <label for="checkbox_terms"></label>
    </li>
    <li class="accept">I have read and accept the terms and conditions</li>
  </ul>
</form>

现在,如果您检查该$scope.myForm.$invalid属性,它将让您知道表单是否已经过验证。

于 2015-01-20T19:26:27.213 回答