确保在角度中选择至少一个复选框

时间:2017-02-13 12:03:11

标签: angularjs

我需要验证是否已选择至少一个3中的复选框。我不能使用单选按钮,因为可以选择两个选项并排除第三个选项。我不确定是否最好将这些复选框放入模型数组中,而不是将它们绑定到单独的模型并创建更长的ng-required表达式。文档对于描述这种事情的“最佳实践”并不是特别有用......

代码:

<div class="form-inline form-group">
<div class="row">
    <div class="col-xs-12">
        <h4 class="card-title left test-list-header">Balcony</h4>
    </div>
</div>

<fieldset class="form-group">
    <input type="checkbox" id="balconyBalcony" ng-model="balcony">
    <label for="balconyBalcony">Balcony</label>
</fieldset>

<fieldset class="form-group">
    <input type="checkbox" id="patioBalcony" ng-model="patio">
    <label for="patioBalcony">Patio</label>
</fieldset>

<fieldset class="form-group">
    <input type="checkbox" id="noBalcony" ng-model="noBalcony" ng-disabled="balcony || patio">
    <label for="noBalcony">No</label>
</fieldset>

<fieldset class="form-group" ng-show="noBalcony && !patio && !balcony">
    <div class="md-form">
        <input
            type="text"
            id="{{ Plot::FIELD_BALCONY_NOTES  }}"
            class="form-control"
            name="{{ Plot::FIELD_BALCONY_NOTES }}"
            inline-edit
            inline-edit-callback="UpdateHandler()"
            ng-model="Model.BalconyNotes.Value"
            ng-class="{ invalid: createPlot.balconyNotes.$invalid && submitted, valid: createPlot.floor.$valid }"
            ng-init="Model.BalconyNotes.Value = '{{ old(Plot::FIELD_BALCONY_NOTES) or $Model->BalconyNotes }}'" ng-required="noBalcony">
        <label for="{{ Plot::FIELD_BALCONY_NOTES }}" data-error="@{{ Model.BalconyNotes.ValidationMessage }}" class="w-100">Comments</label>
        <span class="help-block" ng-show="createPlot.balconyNotes.$invalid && submitted">As there is no balcony or patio, you must enter a comment</span>

    </div>
</fieldset>

2 个答案:

答案 0 :(得分:1)

您可以使用ng-required内置的directive来验证您的表单。

像这样:

<form novalidate name="myForm" ng-submit="mySubmitFunc()">
      <label>Checkbox 1
        <input ng-required="!(cb2 || cb3)" ng-model="cb1" type="checkbox">
      </label>
      <label>Checkbox 2
        <input ng-required="!(cb1 || cb3)" ng-model="cb2" type="checkbox">
      </label>
      <label>Checkbox 3
        <input ng-required="!(cb1 || cb2)" ng-model="cb3" type="checkbox">
      </label>
      <input type="submit" ng-disabled="myForm.$invalid" value="submit">
    </form>

这是一个Using Assembly Language with C,展示了如何处理这种逻辑。

答案 1 :(得分:0)

您可以添加验证行:

<div ng-show="myForm.$submitted">
    <p  style="color: red" ng-show="!myForm.balcony && !myForm.patio && !myForm.noBalcony">You must select at least one of the options above.</p>
</div>

该div显示用户尝试提交的时间,而p显示何时未选择。

您的按钮还需要具有相同条件的ng-disabled指令。