28

我有一个包含 3 个复选框的表单:“选”、“选项 1 ”和“选项 2 ”。

<form id="selectionForm">
    <input type="checkbox" ng-model="selectAll" >Select all
    <br>
    <input type="checkbox" ng-checked="selectAll" checked>Option 1
    <br>
    <input type="checkbox" ng-checked="selectAll">Option 2
</form>

在初始页面加载时,我只想检查 选项 1。然后,如果选中“全选”复选框,则应自动选中“选项 1 ”和“选项 2 ” ,以便全部选中。

问题是在初始页面加载时 ng-checked="selectAll" 被评估,它覆盖了我最初仅检查选项 1 的尝试(最初 selectAll = false),因此没有选择任何内容。

这似乎是一个要解决的简单问题,但我无法找到解决方案......提前感谢您提供任何见解或建议!

4

3 回答 3

85

Another way to go about it is to use a model for the options, set default selection in the model and have your controller handle the logic of doing select all.

angular.module("app", []).controller("ctrl", function($scope){
  
  $scope.options = [
    {value:'Option1', selected:true}, 
    {value:'Option2', selected:false}
  ];
  
  $scope.toggleAll = function() {
     var toggleStatus = !$scope.isAllSelected;
     angular.forEach($scope.options, function(itm){ itm.selected = toggleStatus; });
   
  }
  
  $scope.optionToggled = function(){
    $scope.isAllSelected = $scope.options.every(function(itm){ return itm.selected; })
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js">    </script>
<div ng-app="app" ng-controller="ctrl">
<form id="selectionForm">
    <input type="checkbox" ng-click="toggleAll()" ng-model="isAllSelected">Select all
    <br>
     <div ng-repeat = "option in options">
        <input type="checkbox" ng-model="option.selected" ng-change="optionToggled()">{{option.value}}
     </div>
</form>
  {{options}} 
</div>

于 2014-12-12T21:20:06.690 回答
5

我喜欢使用 ng-repeat 来清楚地显示你正在选择/取消选择的内容,基本上你最终会得到一个很好的小对象来作为它的基础,并且添加它更容易。

这是一个Plunker

*还要注意如何实现 allSelected?使用循环函数而不是大量 html,我相信这可以用更少的意大利面条来完成,但它可以工作*

app.controller('MainCtrl', function($scope) {

$scope.allSelected = false;

$scope.checkboxes = [{label: 'Option 1',checked: true}, {label: 'Option 2'}}}];

$scope.cbChecked = function(){
  $scope.allSelected = true;
  angular.forEach($scope.checkboxes, function(v, k) {
    if(!v.checked){
      $scope.allSelected = false;
    }
  });
}
$scope.toggleAll = function() {
    var bool = true;
    if ($scope.allSelected) {
      bool = false;
    }
    angular.forEach($scope.checkboxes, function(v, k) {
      v.checked = !bool;
      $scope.allSelected = !bool;
      });
   }
});
于 2014-12-12T21:33:58.620 回答
5

尝试这个:

<form id="selectionForm">
    <input type="checkbox" ng-model="selectAll" >Select all
    <br>
    <input type="checkbox" ng-checked="selectAll || option1" ng-init="option1=true" ng-model="option1">Option 1
    <br>
    <input type="checkbox" ng-checked="selectAll">Option 2
</form>
于 2014-12-12T21:11:13.807 回答