在AngularJS中单击按钮时将复选框设置为默认值

时间:2017-01-11 09:04:27

标签: angularjs

我正在使用AngularJs,其中我有一个复选框集合,并已将其中一个项目设置为已选中。 index.cshtml具有以下代码:

  <div ng-controller="testController" ng-init="init()">
    <form name="mainForm" id="createForm" ng-submit="mainForm.$valid && add()" novalidate="">
      <div class="container" ng-show="createMenu">
        <div class="row">
          <div class="col-lg-2 col-md-2 col-sm-2 ">
            <label>Delivery Method</label>
          </div>
          <div class="col-lg-2 col-md-2 col-sm-2" 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="button" id="btnReset" value="Cancel" ng-click="reset()" />
      </div>
    </form>
  </div>

复选框数据在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
}];

这里&#34;测试&#34;默认选中。如果我选择选项&#34;测试两个&#34;然后点击取消,我想设置复选框&#34; test-up&#34;如选中。我尝试了以下代码,但无法正常工作:

$scope.clear = function() {
  $scope.deliverySelection = ["test-up"];
  $scope.submitted = false;
  $scope.clearAll();
}

$scope.reset = function() {
  $scope.clear();
}
$scope.toggleSelection = function toggleSelection(deliveryMethods) {
  var idx = $scope.deliverySelection.indexOf(deliveryMethods);
  // is currently selected
  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.length; i++) {
    if ($scope.deliveryMethods[i].selected == true) {
      $scope.someSelected = true;
      return false;
    }
  }
}


$scope.clearAll = function() {
  angular.forEach($scope.deliveryMethods, function(checkbox_id) {
    if (checkbox_id.id != 1)
      checkbox_id.selected = false;
  });

}

如何设置复选框&#34;测试&#34;如果选中,点击取消按钮? 感谢

1 个答案:

答案 0 :(得分:1)

尝试这个而不是清除所有功能

$scope.clearAll = function() {
  angular.forEach($scope.deliveryMethods, function(checkbox_id) {
    checkbox_id.selected = false;
    if (checkbox_id.id == 1) {
      checkbox_id.selected = true;
    }
  });
}