廚老伯開槍中

Angular: 簡單的 Pager 作法

AngularJS 處理分頁蠻簡單的
不過以下範例要用在資料數目很大的頁面時,會需要額外的處理

function dataList($scope) {
    $scope.list=[
  {name: '第一筆'}
  //,以下類推...
  ,{name: '最後一筆'}];
  
  //宣告放置目前顯示資料的陣列
  $scope.currentList=[]; 
  
//使用 click 事件更換 currentlist 內容,讓 angularJS自動處理顯示工作
  $scope.pageCurrent = 1;  //預設頁面
    $scope.pagePageSize = 6; //每個頁面資料數目
    $scope.pageMax = function () { //取得最大頁數
        return Math.ceil($scope.storeList.length / $scope.pagePageSize);};
    $scope.changePage = function(aPageIndex) {
        if(aPageIndex == 'next' && ($scope.pageCurrent < $scope.pageMax())) //判斷是否超過 MAX
            $scope.pageCurrent++;
        else if(aPageIndex == 'prev' && (parseInt($scope.pageCurrent) > 1))
            $scope.pageCurrent--;
        else if(aPageIndex == 'last')
            $scope.pageCurrent = $scope.pageMax();
        else if(aPageIndex == 'first')
            $scope.pageCurrent = 1;
// 更新 currentList
  $scope.currentList = [];
  //避免爆表
  var ii = Math.min($scope.pageCurrent * $scope.pagePageSize, $scope.storeList.length);         
  for (var i = ($scope.pageCurrent - 1) * $scope.pagePageSize; i < ii; i++) {
    $scope.currentList.push($scope.storeList[i]);
  }
}
}
<div ng-controller='dataList'>
  <div ng-model="currentList">
    <div ng-repeat ="c in currentList">{{c.name}}</div>
  </div>
  <div ng-click='changePage("first")'>第一頁</div>
  <div ng-click='changePage("prev")'>上一頁</div>
  <div ng-click='changePage("next")'>下一頁</div>
  <div ng-click='changePage("last")'>最後一頁</div>
</div>
comments powered by Disqus