在前台开发过程中,列表批量选择是一个开发人员经常遇到的功能,列表批量选择的实现方式很多,但是原理基本相同,本文主要来讲AngularJs如何简单的实现列表批量选择功能。
首先来看html代码
1 <table cellpadding="0" cellspacing="0" border="0" class="datatable table table-hover dataTable"> 2 <thead> 3 <tr> 4 <th><input type="checkbox" ng-click="selectAll($event)" ng-checked="isSelectedAll()"/></th> 5 <th>姓名</th> 6 <th>单位</th> 7 <th>电话</th> 8 </tr> 9 </thead> 10 <tbody> 11 <tr ng-repeat="item in content"> 12 <td><input type="checkbox" name="selected" ng-checked="isSelected(item.id)" ng-click="updateSelection($event,item.id)"/></td> 13 <td>{{item.baseInfo.name}}</td> 14 <td>{{item.orgCompanyName}}</td> 15 <td>{{item.baseInfo.mobileNumberList[0].value}}</td> 16 </tr> 17 </tbody> 18 </table>
html里面简单建立一个表格,与批量选择相关的只有两处。
一处是第3行 ng-click="selectAll($event)" ,用来做全选的操作; ng-checked="isSelectedAll() 用来判断当前列表内容是否被全选。
一处是第12行 ng-click="updateSelection($event,item.id) ,用来对某一列数据进行选择操作; ng-checked="isSelected(item.id) 用来判断当前列数据是否被选中。
然后需要在与该页面相对应的controller中实现与批量选择相关的方法
1 //创建变量用来保存选中结果 2 $scope.selected = []; 3 var updateSelected = function (action, id) { 4 if (action == 'add' && $scope.selected.indexOf(id) == -1) $scope.selected.push(id); 5 if (action == 'remove' && $scope.selected.indexOf(id) != -1) $scope.selected.splice($scope.selected.indexOf(id), 1); 6 }; 7 //更新某一列数据的选择 8 $scope.updateSelection = function ($event, id) { 9 var checkbox = $event.target; 10 var action = (checkbox.checked ? 'add' : 'remove'); 11 updateSelected(action, id); 12 }; 13 //全选操作 14 $scope.selectAll = function ($event) { 15 var checkbox = $event.target; 16 var action = (checkbox.checked ? 'add' : 'remove'); 17 for (var i = 0; i < $scope.content.length; i++) { 18 var contact = $scope.content[i]; 19 updateSelected(action, contact.id); 20 } 21 }; 22 $scope.isSelected = function (id) { 23 return $scope.selected.indexOf(id) >= 0; 24 }; 25 $scope.isSelectedAll = function () { 26 return $scope.selected.length === $scope.content.length; 27 };
controller中主要是对html中用到的几个方法的实现,相对来讲实现代码还是比较简洁易懂的。
多选效果展示如下