1

我在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;
            }
        }
    }

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

4

2 回答 2

1

尝试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;
   }
}

更新

但没有显示错误消息。如何更新错误消息如下复选框以显示错误

更新您的跨度代码,如下所示

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

并且请someSelected()在初始阶段和每个复选框单击事件中致电您。

于 2017-01-04T07:52:51.710 回答
0

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

于 2017-01-04T09:14:55.760 回答