在角

2015-06-12 27 views
1

使用AND运算我有以下HTML在角

<input type="checkbox" id="cbxSelectAllPreventive"/> <label>Select All</label> 
    <ul style="list-style: none;"> 
     <li ng-repeat="test in lists.Tests"> 
     </li> 
    </ul> 

测试是具有IsSelected属性复杂的对象的阵列。 我想使用复选框作为SelectAll功能。 要做到这一点,我需要提供ng-model到复选框,我可以提供它作为一种方法,检查每个测试并返回true/false。有没有办法做到这一点,没有写一个方法?

回答

2

我只看到一个办法做到这一点使用功能上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

+0

另一个添加问题,我如何更改文本以在同一场景中选择All/Deselect all? – SJMan

+0

在我看来,这不是你唯一需要追踪的东西。显然你会有一个选择单个项目的机制,它也应该被反映出来。你将不得不建立一个[三态复选框](http://www.software-architects.com/devblog/2015/02/26/Tri-State-Check-Box-in-HTML-with-AngularJS-and -TypeScript)。在我更新的答案中,我提出了一个想法何时应该放弃它 –

0

你尝试ng-checkbox是应该做的exaclty什么

+0

究竟它是如何帮助修改范围列表中没有'$ scope'额外的功能? –