angularjs 实现多选框分段全选效果
在前台开发过程中,列表批量选择是一个开发人员经常遇到的功能,列表批量选择的实现方式很多,但是原理基本相同,本文主要来讲AngularJs如何简单的实现列表批量选择功能。
效果如下
image.png
首先来看html代码
<div class="form-group1" > <div class="input-group"> <div class="input-group-addon no-border" > <p>角色权限:</p> </div> </div></div><div class="" ng-repeat="todotype in todolist" > <div class="" > <div class="" > <input type="checkbox" ng-model="$parent.selectAll[$index]" ng-click="changeAll($index)" /> <span > {{todotype.type}} </span> </div> <div class="" > <div class="row"> <div class="col-md-2 col-sm-2" ng-repeat="obj in todolist[$index].permissionList" > <input type="checkbox" ng-click="funcChange($parent.$index)" ng-model="obj.isSelected" /> <span >{{obj.name}}</span> </div> </div> </div> </div></div>
html里面简单建立一个表格,与批量选择相关的只有两处。
一处是ng-click="changeAll($index)
,用来做全选的操作;ng-click="funcChange($parent.$index)"
用来判断当前大类里内容是否被全选。判断是否全选是用
ng-model
进行判断 第一处ng-model="$parent.selectAll[$index]"
是判断这一大类是否全选;ng-model="obj.isSelected"
是判断每一大类的每一项的选择;接下来是控制器里的代码也就是js文件
// 获取数据 这里具体post请求就不写了 $scope.todolist = res.data.data; for(var i = 0; i < $scope.todolist.length; i++) { angular.forEach($scope.todolist[i].permissionList, function(i) { i.isSelected = false; }) }// 数据类型如下 $scope.list = [{ permissionList: [{ 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 } ], type: "制造资源管理" }, { permissionList: [{ name: 'Golde1', // birthday: '2000-01-10', isSelected: false }, { name: 'King1', // birthday: '1990-01-10', isSelected: false }, { name: 'Mark1', // birthday: '19890-01-10', isSelected: false }, { name: 'Marie1', // birthday: '2010-01-10', isSelected: false } ], type: "制造资源管理2" }, { permissionList: [{ name: 'Golde2', // birthday: '2000-01-10', isSelected: false }, { name: 'King2', // birthday: '1990-01-10', isSelected: false }, { name: 'Mark2', // birthday: '19890-01-10', isSelected: false }, { name: 'Marie2', // birthday: '2010-01-10', isSelected: false } ], type: "制造资源管理3" }];// 具体方法如下所示 // 这里初始化数组 上来全为空 $scope.selectAll = []; // 对于对象进行操作的时候(点击),会执行funcChange // 判断对象数组中isSelected 是否为 true或false,在决定select是否为true $scope.changeAll = function(index) { //全选/取消全选 angular.forEach($scope.todolist[index].permissionList, function(v, k) { v.isSelected = $scope.selectAll[index]; }) }; $scope.funcChange = function(index) { // 当所有都选中时 $scope.selectAll[index] = true; angular.forEach($scope.todolist[index].permissionList, function(v, k) { $scope.selectAll[index] = $scope.selectAll[index] && v.isSelected; }); };
具体逻辑已经写得很清楚 不懂得地方或者不好的地方欢迎在在评论多多评论!
作者:Skywang
链接:https://www.jianshu.com/p/492e3a4a3337