angularjs全选框及复选框功能,切换分页时保留选中状态

在切换分页时保持之前页的选中状态,选中的值的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;

}

}

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值