之前在百度上找了很多关于用AngularJS实现checkbox全选的功能,但是都只能完成部分功能,下面将需要的功能列出如下:
1、将所有请选择向的checkbox都选中时,上面的全选也选中。
2、如有一个没有选中,全选取消。
3、点击查看按钮,查看选中的名字有哪些。
在网上找了很多资料,发现很多的都是只能实现前面2个功能,而且还有一点复杂,最后在API上查了一下用ngChecked这个指令可以很轻松的实现这个功能。代码如下
html:
<div ng-controller = 'myCtrl'>
<button ng-click="checkStatus()">查看</button>
<input type = "checkbox" ng-model="selectAll" ng-checked="select" ng-click="changeAll()"/>全选/取消全选 <br/>
<table width="50%">
<thead>
<tr>
<th>请选择</th>
<th>姓名</th>
<th>生日</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="obj in list">
<td>
<input type = "checkbox" ng-checked="selectAll" ng-click="funcChange()" ng-model="obj.isSelected"/>
</td>
<td>{{obj.name}}</td>
<td>{{obj.birthday}}</td>
</tr>
</tbody>
</table>
</div>
js:<script>
var app = angular.module("myApp", ['ng']);
app.controller('myCtrl', function ($scope) {
$scope.list = [
{name:'Golde',birthday:'2000-01-10',isSelected:false},
{name:'King',birthday:'1990-01-10',isSelected:false},
{name:'Mark',birthday:'19890-01-10',isSelected:false},
{name:'Marie',birthday:'2010-01-10',isSelected:false}
];
$scope.checkStatus = function(){
var str = '';
angular.forEach($scope.list,function(value,key){
if(value.isSelected){
str += value.name+"被选中了\n";
}
});
if(str === ''){
str = '都未选中';
}
alert(str);
};
// 对于对象进行操作的时候(点击),会执行funcChange
// 判断对象数组中isSelected 是否为 true或false,在决定select是否为true
$scope.changeAll = function(){//全选/取消全选
angular.forEach($scope.list,function(v,k){
v.isSelected = $scope.selectAll;
})
};
$scope.funcChange = function(){// 当所有都选中时
$scope.select = true;
angular.forEach($scope.list,function(v,k){
$scope.select = $scope.select && v.isSelected;
});
};
});
</script>
大家可以试试用这个方法。