我只看到一个办法做到这一点使用功能上ng-change
<input type="checkbox" id="cbxSelectAllPreventive"
ng-model="checked" ng-change="setAll(checked)"/>
...
$scope.setAll = function(isSelected){
$scope.lists.Tests.map(function(el){
el.isSelected = isSelected;
})
}
工作fiddle
编辑:
对于完成项目选择和复选框之间的双向连接,代码会稍微复杂一些。
我们将在$scope
中使用一个额外的变量来反映复选框的标签。不要忘了初始化变量在控制器创建
<label for="cbxSelectAllPreventive">{{selectLabel}}</label>
...
$scope.selectLabel = 'Select All';
setAll
功能应该设置这个变量的照顾。
$scope.setAll = function(isSelected){
$scope.selectLabel = isSelected ? 'Deselect All' : 'Select All';
$scope.lists.Tests.map(function(el){
el.isSelected = isSelected;
})
}
最后你肯定会有选择/取消选择单个项目的选项。对于这种情况下,你必须$watch
你的清单。注意第三个参数true
,它进行深度比较,否则它不会“注意”对象内部的变化。
$scope.$watch('lists.Tests', function(){
var text = $scope.lists.Tests.map(function(el){ return el.isSelected; }).join();
console.log(text);
var allSelected = $scope.lists.Tests.every(function(el){ return el.isSelected;});
var noneSelected = $scope.lists.Tests.every(function(el){ return !el.isSelected;});
if(noneSelected){
$scope.selectLabel = 'Select All';
$scope.checked = false;
}else if(allSelected){
$scope.selectLabel = 'Deselect All';
$scope.checked = true;
}
if(!noneSelected && !allSelected) {
$scope.selectLabel = 'Undetermined';
// here set the check box to undetermined (third) state
}
}, true);
Updated fiddle
另一个添加问题,我如何更改文本以在同一场景中选择All/Deselect all? – SJMan
在我看来,这不是你唯一需要追踪的东西。显然你会有一个选择单个项目的机制,它也应该被反映出来。你将不得不建立一个[三态复选框](http://www.software-architects.com/devblog/2015/02/26/Tri-State-Check-Box-in-HTML-with-AngularJS-and -TypeScript)。在我更新的答案中,我提出了一个想法何时应该放弃它 –