我有一个包含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最初)的尝试,因此没有选择任何内容.
解决方法
另一种方法是使用模型的选项,在模型中设置默认选择,并让您的控制器处理所有选择的逻辑.
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>