angularjs的全选与反选

最近项目用了angular框架,正好需要用到全选反选,在这里整理了一下......

这里只适合刚学习angular的小伙伴们稍作参考,如有不对的地方,还请指教......

接下来......

上代码......

在这里说明一下,此处是放在表格里面循环出来的 全选框和单选框......

 1 <table class="sel_table" width="100%" cellpadding="0" cellspacing="0">
 2    <thead>
 3       <th><input type="checkbox" ng-model="select_all" ng-change="selectAll()" />全选</th>
10    </thead>
11    <tbody>
12    <tr ng-repeat="device in list.devices" ng-if="list.devices.length>0">
13          <td><input type="checkbox" ng-value="{{device.deviceId}}" ng-model="device.checked" ng-change="selectOne()"/></td>
46    </tr>
47    <tr ng-if="list.devices==0">
48       <td>暂无数据!</td>
49    </tr>
50    </tbody>
51 </table>
 1  //单选或多选删除
 4     $scope.checked = []; //定义一个数组 存入id或者想要用来交互的参数...
 7     $scope.selectAll = function () {
 8         if ($scope.select_all) { //判断是全选
 9             $scope.checked = [];//先清空,防止在操作了一个轮回之后,重复添加了...12             angular.forEach($scope.list.devices, function (i) {  //list.devices这是循环从后台获取的数组,并添加到刚刚定义的数组里
13                 i.checked = true; //全选即将所有的复选框变为选中
14                 $scope.checked.push(i.deviceId);//将选中的内容放到数组里26             })
27         } else {//判断全不选
28             angular.forEach($scope.list.devices, function (i) {
29                 i.checked = false; //所有复选框为不选中
30                 $scope.checked = [];//将数组清空33             })
34         }
36     };
37     $scope.selectOne = function () {//下面的复选框单独点击
38         angular.forEach($scope.list.devices, function (i) {//依旧是循环......
39             var index = $scope.checked.indexOf(i.deviceId);//检索checked中是否有i.deviceId 如果没有则会返回-1
40             if (i.checked && index === -1) { 52                 $scope.checked.push(i.deviceId);
53             } else if (!i.checked && index !== -1) {
54                 $scope.checked.splice(index, 1);57             }
58         })
60         if ($scope.list.devices.length === $scope.checked.length) {//判断checked数组的长度是否与原来请求的后台数组的长度是否相等 即是否给全选框加上选中
61             $scope.select_all = true;
62         } else {
63             $scope.select_all = false;
64         }
66     }

                                         

如上图 为页面刚开始的视图......

接下来开始测试......

          

这里是点击全选这个复选框之后,所有的复选框都被选中,没问题~

          

再次点击全选框,所有的复选框都没有选中,没毛病~

          

在全选的状态下,点击第一个复选框,复选框变为没有选中,全选框也没有选中了,那么就说明完成啦~

emmmm......

就酱紫啦,乱七八糟的摆了一通,留待以后改进~

猜你喜欢

转载自www.cnblogs.com/nanabing/p/9714429.html