在切换分页时保持之前页的选中状态,选中的值的id都存在$scope.Ids里,设置一个baseController,用到这个功能的Controller都可以直接继承使用
初学者,希望大家可以指出错误和不足
在全选框标签内绑定:ng-model="select_all" ng-change="selectAll()"
复选框标签内绑定:ng-model="entity.checked" ng-change="selectOne(entity)"
在reload方法(切换分页时刷新页面的方法)末添加:$scope.isContained();
将以下代码添加到baseController内
$scope.Ids = [];
//全选
$scope.selectAll = function() {
//alert(JSON.stringify($scope.list))
if ($scope.select_all) {
//全选选中,则添加当前页面记录的id到Ids
angular.forEach($scope.list, function(entity) {
//判断是否已经在Ids内,防止重复添加
var index = $scope.Ids.indexOf(entity.id);
//如果不存在,则添加并设置复选框为选中状态
if (index == -1) {
entity.checked = true;
$scope.Ids.push(entity.id);
}
})
} else {
angular.forEach($scope.list, function(entity) {
//取消全选,则从Ids中删除当前页面记录的id
var index = $scope.Ids.indexOf(entity.id);
if (index != -1) {
entity.checked = false;
$scope.Ids.splice(index,1);
}
})
}
}
//单选
$scope.selectOne = function(entity) {
var index = $scope.Ids.indexOf(entity.id);
if (entity.checked && index == -1) {
$scope.Ids.push(entity.id);
$scope.isContained();
} else {
$scope.Ids.splice(index, 1);
//取消选中任意一条记录,则全选框为false
$scope.select_all = false;
}
}
//切换分页时恢复选中状态
$scope.isContained = function(){
//判断当前页面记录的ID是否在Ids中存在,如果存在则设置该行选中状态为true
for(var i = 0;i<$scope.list.length;i++){
var index = $scope.Ids.indexOf($scope.list[i].id);
if(index != -1){
$scope.list[i].checked= true;
}
}
//判断当前页ID是否全部在Ids中存在,如果有一条不存在,则设置select_all = false,如果全部存在则设置$scope.select_all = true
for(var i = 0;i<$scope.list.length;i++){
if($scope.list[i].checked == null ||$scope.list[i].checked != true){
$scope.select_all = false;
break;
}
$scope.select_all = true;
}
}