學習任何一門語言前確定是有業務需求來驅動你去學習它,固然ng也不例外,在學習ng前我第一個想作的demo就是基於ng實現分頁,除去基本的計算思路外就是使用指令封裝成一個插件,在須要分頁的列表頁面內直接引用。javascript
在封裝分頁插件時我實現了幾種方式整體都比較零散,最後找到了一個朋友(http://www.miaoyueyue.com/archives/813.html)封裝的插件,覺還不錯,讀了下他的源碼就直接在項目中使用了。html
一、插件源碼主要基於angular directive來實現。java
二、調用時關鍵地方是後臺請求處理函數,也就是從後臺取數據。app
三、插件有兩個關鍵參數currentPage、itemsPerPage,當前頁碼和每頁的記錄數。函數
四、實現方法調用後咱們須要根據每次點擊分頁插件頁碼時從新提交後臺來獲取相應頁碼數據。 在調用的頁碼中我使用了$watch來監控。 我初次使用時是把調用函數放在了插件的onchange中,結果發現每次都會觸發兩次後臺。這個地方須要注意。post
五、我把請求後臺封裝成了Service層,而後在Controller裏調用,也符合MVC思想。學習
1 <div ng-app="DemoApp" ng-controller="DemoController"> 2 <table class="table table-striped"> 3 <thead> 4 <tr> 5 <td>ID</td> 6 <td>FirstName</td> 7 <td>LastName</td> 8 <td>Status</td> 9 <td>Address</td> 10 </tr> 11 </thead> 12 <tbody> 13 <tr ng-repeat="emp in persons"> 14 <td>{{emp.ID}}</td> 15 <td>{{emp.FirstName}}</td> 16 <td>{{emp.LastName}}</td> 17 <td>{{emp.Status}}</td> 18 <td>{{emp.Address}}</td> 19 </tr> 20 </tbody> 21 </table> 22 <tm-pagination conf="paginationConf"></tm-pagination> 23 </div> 24 <script type="text/javascript"> 25 var app = angular.module('DemoApp', ['tm.pagination']); 26 27 app.controller('DemoController', ['$scope', 'BusinessService', function ($scope, BusinessService) { 28 29 var GetAllEmployee = function () { 30 31 var postData = { 32 pageIndex: $scope.paginationConf.currentPage, 33 pageSize: $scope.paginationConf.itemsPerPage 34 } 35 36 BusinessService.list(postData).success(function (response) { 37 $scope.paginationConf.totalItems = response.count; 38 $scope.persons = response.items; 39 }); 40 41 } 42 43 //配置分頁基本參數 44 $scope.paginationConf = { 45 currentPage: 1, 46 itemsPerPage: 5 47 }; 48 49 /*************************************************************** 50 當頁碼和頁面記錄數發生變化時監控後臺查詢 51 若是把currentPage和itemsPerPage分開監控的話則會觸發兩次後臺事件。 52 ***************************************************************/ 53 $scope.$watch('paginationConf.currentPage + paginationConf.itemsPerPage', GetAllEmployee); 54 }]); 55 56 57 //業務類 58 app.factory('BusinessService', ['$http', function ($http) { 59 var list = function (postData) { 60 return $http.post('/Employee/GetAllEmployee', postData); 61 } 62 63 return { 64 list: function (postData) { 65 return list(postData); 66 } 67 } 68 }]); 69 </script>