【问题标题】:Validating group of checkboxes in Angular验证Angular中的复选框组
【发布时间】:2015-06-17 06:19:42
【问题描述】:

只是想知道如何以角度验证一组复选框,以便在没有选择它们并且它们是 $dirty 时,会显示一条错误消息。

我不确定我做错了什么,但没有为它们设置 $dirty - 必须选择最后一个才能设置 $dirty。当组中的一个复选框被触摸时,我希望设置 $dirty。我编写了一个自定义 ng-required 规则,用于检查其中一个复选框是否已被选中。

请戳这里:http://plnkr.co/edit/lDYMXSZcCOjmBSMC7kHQ?p=info

<div class="checkbox checkbox-inline checkbox-icons" ng-repeat="type in serviceTypes" ng-if="newListing.isService" ng-click="print(newListing)">
    <input type="checkbox" id="{{type.icon}}" ng-model="newListing.listingTypes[type.typeId]" name="inputListingType" ng-required="!oneCheckboxSelected(newListing.listingTypes)">
    <label for="{{type.icon}}">
        {{type.name}}
    </label>
</div>
<small class="help-block" ng-messages="addSpaceForm.inputListingType.$error" ng-show="addSpaceForm.inputListingType.$dirty">
    <span ng-message="required">This field is required</span>
</small>

在控制器中:

$scope.oneCheckboxSelected = function(arr) {
    return _.keys(_.pick(arr, _.identity)).length > 0;
};

【问题讨论】:

标签: javascript angularjs


【解决方案1】:

之所以出现此问题,是因为您正试图检查一个表单元素的$dirty 属性,该元素有许多具有相同的name。这不起作用,因为 Angular 无法将属性绑定到许多元素。

考虑使用http://vitalets.github.io/checklist-model/,这是一个可安装的依赖项,用于在一个指令中处理多个复选框。

您应该能够使用checklist-change="imChanged()" 的自定义函数来切换您的验证消息块

【讨论】:

    猜你喜欢
    • 2019-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-21
    • 2013-11-07
    • 2013-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多