在前台開發過程中,列表批量選擇是一個開發人員經常遇到的功能,列表批量選擇的實現方式很多,但是原理基本相同,本文主要來講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中用到的幾個方法的實現,相對來講實現代碼還是比較簡潔易懂的。
多選效果展示如下