Angular Form验证以显示错误消息

时间:2015-12-01 20:15:31

标签: javascript jquery angularjs forms checkbox

我有一个表单,我想在没有选中任何复选框时显示内联错误消息。但是我无法显示以下情况的消息

我有一个带有两个无线电选项的表格 - 不,是的。当用户选择是时,他可以选择从复选框列表中选择值。当用户选择是单选按钮时,他应该选择至少一个复选框,否则应显示错误消息,提示用户至少选择一个复选框值。如果单选选项为否,则不需要选择复选框。我如何使用角度形式验证来实现这一目标?

 <p ng-if="noCheckboxSlected" class="form-error"><img src="images/icon-error.png" alt=""/>Sorry, please select a option.</p>
        <form name="answersToQuestions">
        <div class="ice-form-radio">
             <input type="radio" name="mpq{{allergies.questionId}}" ng-model="allergies.answer" ng-click="setQuestion(false)" value="no">
             <label for="mpq{{allergies.questionId}}no"><span>No </span></label>
        </div>
            <div class="ice-form-radio">
                <input type="radio" name="mpq{{questionId}}"  ng-model="allergies.answer" value="yes" ng-click="setCondition(true)"/>
                <label for="mpq{{questionId}}yes"><span>Yes</span></label>
            </div>
            <table>
                <tr ng-repeat="(key, allergyList) in  filteredAllergies track by $index">
                    <td ng-repeat="allergy in allergyList track by $index">
                        <div class="ice-form-checkbox">
                            <input id="condition-{{allergy.allergyCode}}" ng-model="allergy.allergyIndicator" type="checkbox" />
                            <label for="condition-{{allergy.allergyCode}}"><span>{{allergy.allergyName}}</span></label>
                        </div>
                    </td>
                </tr>
            </table>
        </div>
        </form>

由于

1 个答案:

答案 0 :(得分:0)

首先,您应该使用ng-change而不是ng-click输入。 当输入值发生变化时触发更改。

仍在使用ng-change,您可以在控制器中编写一个方法,检查是否至少检查了一个复选框并将变量设置为true或false:

<tr ng-repeat="(key, allergyList) in  filteredAllergies track by $index">
  <td ng-repeat="allergy in allergyList track by $index">
    <div class="ice-form-checkbox">
       <!-- put ng-change here -->
      <input id="condition-{{allergy.allergyCode}}" ng-model="allergy.allergyIndicator" type="checkbox" ng-change="checkOnce()"/>
      <label for="condition-{{allergy.allergyCode}}"><span>{{allergy.allergyName}}</span></label>
    </div>
  </td>
</tr>

并在您的控制器中:

$scope.onceIsCheck = false;
$scope.checkChange = function () {
  $scope.onceIsCheck = false;
  for (var i = 0; i < $scope.filteredAllergies.length; ++i) {
     if($scope.filteredAllergies[i].allergyIndicator) {
       $scope.onceIsCheck = true;
     }
  }
};

在您看来:

<p ng-if="onceIfCheck">You have to check at least one item</p>