AngularJs实现全选功能
html代码
<!-- 数据表格 --> <div class="table-box"> <!--工具栏--> <div class="pull-left"> <div class="form-group form-inline"> <div class="btn-group"> <button type="button" class="btn btn-default" title="新建" data-toggle="modal" data-target="#editModal" ng-click="entity={}"><i class="fa fa-file-o"></i> 新建 </button> <button type="button" class="btn btn-default" title="删除"><i class="fa fa-trash-o"></i> 删除</button> <button type="button" class="btn btn-default" title="刷新" onclick="window.location.reload();"><i class="fa fa-refresh"></i> 刷新 </button> </div> </div> </div> <div class="box-tools pull-right"> <div class="has-feedback"> 品牌名称:<input ng-model="searchEntity.name"> 品牌首字母:<input ng-model="searchEntity.firstChar"> <button class="btn btn-default" ng-click="reloadList()">查询</button> </div> </div> <!--工具栏/--> <!--数据列表--> <table id="dataList" class="table table-bordered table-striped table-hover dataTable"> <thead> <tr> <th class="" style="padding-right:0px"> <input id="selall" type="checkbox" class="icheckbox_square-blue" ng-checked="ifCheckedAll()" ng-click="selectAll($event)"> </th> <th class="sorting_asc" >品牌ID</th> <th class="sorting">品牌名称</th> <th class="sorting">品牌首字母</th> <th class="text-center">操作</th> </tr> </thead> <tbody> {{selectIds}} <tr ng-repeat="entity in list"> <td><input type="checkbox" ng-click="updateSelection($event,entity.id)" ng-checked="ifChecked(entity.id)"></td> <td>{{entity.id}}</td> <td>{{entity.name}}</td> <td>{{entity.firstChar}}</td> <td class="text-center"> <button type="button" class="btn bg-olive btn-xs" data-toggle="modal" data-target="#editModal" ng-click="selectByOne(entity.id)">修改 </button> </td> </tr> </tbody> </table>
js代码
//更新复选 $scope.selectIds=[];//选中的ID集合 $scope.updateSelection=function ($event, id) { if ($event.target.checked){//如果被选中,则添加到数组中 $scope.selectIds.push(id); }else { var index = $scope.selectIds.indexOf(id); $scope.selectIds.splice(index,1);//其中index表示删除的位置,1表示删除一个 } }; $scope.ifChecked=function (id) { //如果Id出现在数组中,则需要返回true var index=$scope.selectIds.indexOf(id); if (index==-1){ return false; }else {//如果id没有出现在selectIds数组中需要返回false return true; } }; $scope.ifCheckedAll=function () { //$scope.list中的对象的id 是否都在 $scope.selectIds中 //如果全中,则返回true //如果有一个还在,就返回false alert("ifCheckAll"); for (var i = 0; i < $scope.list.length; i++) { if ($scope.selectIds.indexOf($scope.selectIds[i])==-1){ return false; } } return true; }; //全选与取消全选 $scope.selectAll=function ($event) { alert("dfadfas"); if ($event.target.checked){ for (var i = 0; i < $scope.list.length; i++) { //当前页面的数据的id放到数组中 if ($scope.selectIds.indexOf($scope.list[i].id)==-1){ $scope.selectIds.push($scope.list[i].id); } } }else{ for (var i=0;i<$scope.list.length;i++){ var index=$scope.selectIds.indexOf($scope.list[i].id); $scope.selectIds.splice(index); } } };