取消选中复选框以使表单无效

时间:2015-01-20 19:16:06

标签: angularjs angularjs-ng-model angularjs-validation

尝试为表单中的复选框添加表单验证器,如果未选中该表单,则表单将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可以触发添加{{1}}的任何建议,反之亦然。

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分:1)

嗯,对于初学者来说,这不是一种形式。如果你想保留这个结构,你可以简单地在复选框上应用一个模型,并放置一个&#34;无效的&#34;属性有条件地取决于$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属性,它会通知您表单是否已经过验证。