最近項目用了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......
就醬紫啦,亂七八糟的擺了一通,留待以后改進~