ng-复选框必需

ng-Required for Checkbox

我在 index.html 中添加了一组复选框控件。我想检查当用户单击提交按钮时是否至少选中了一个复选框。我尝试了下面的代码,但它似乎不起作用。

在index.html中:

    <form name="mainForm" id="createForm" ng-submit="mainForm.$valid && add()" novalidate="">  
      <div >
                          <label>Delivery Method</label>
                      </div>
                      <div ng-repeat="method in deliveryMethods">
                          <input type="checkbox" id="{{method.id}}"
                                 value="{{method.value}}" name="deliveryMethod[]" ng-model="method.selected"
                                 ng-click="toggleSelection(method.value)" ng-required="!someSelected">
                          {{method.value}}

                      </div>

                  </div>
                  <span style="color:red" ng-show="submitted == true &&  !someSelected">Delivery is required</span>         
<input type="submit" value="Submit" ng-click="submitted=true" /> 

在controller.js文件中,

$scope.deliveryMethods = [{
            "id": 1,
            "value": "Test-up",
            selected: true
        }, {
            "id": 2,
            "value": "Test Two",

            selected: false
        }, {
            "id": 3,
            "value": "Test Three",

            selected: false
        }];      

 $scope.toggleSelection = function toggleSelection(deliveryMethods) {       
        var idx = $scope.deliverySelection.indexOf(deliveryMethods);
                    if (idx > -1) {
            $scope.deliverySelection.splice(idx, 1);
        } else {
            $scope.deliverySelection.push(deliveryMethods);
        }
        someSelected();
    };
$scope.someSelected = true;
    function someSelected() {
        $scope.someSelected = false;
        for (var i = 0; i < $scope.deliveryMethods.lenght; i++) {
            if ($scope.deliveryMethods[i].selected == true) {
                $scope.someSelected = true;                   
                return false;
            }
        }
    }

我想检查一下,当用户点击提交按钮时,是否至少选中了一个复选框。如果未选中复选框,则显示带有自定义消息的跨度。 如何解决这个问题? 谢谢

尝试 calculateSomeSelected 循环

$scope.someSelected=false;
for (var i=0;i<$scope.deliveryMethods.lenght;i++)
{
   if($scope.deliveryMethods[i].selected == true)
   {
      $scope.someSelected=true;
      // show custom message here
      return false;
   }
}

更新

but there is no error message getting shown. How to update the error message as below for checkbox to show the error

像下面这样更新你的跨度代码

<span style="color:red" ng-show="submitted == true && !someSelected">Name is required</span> 

另外请在初始阶段和每个复选框单击事件中调用您的 someSelected()

您可以在提交按钮上使用 ng-disabledng-if 作为解决方法,并为此使用一个标志。 这是工作 Fiddle.