下面我们来看一下angularjs是怎么实现分页的:
1、首先在页面创建按钮区:
<!-- 分页按钮 --> <div> <ul class="pagination pull-right"> <li> <a href ng-click="prev()">上一页</a> </li> <li ng-repeat="page in pageList" ng-class="{active:isActivePage(page)}"> <a href="" ng-click="selectPage(page)">{{page}}</a> </li> <li> <a href ng-click="next()">下一页</a> </li> </ul> </div>
2、然后编写脚本,读取资源并生成分页按钮:
<script type="text/javascript" charset="utf-8"> //1. 初始化 paginationApp 模块 ,其中 [] 为依赖列表 var paginationApp = angular.module("paginationApp",[]); //2. 初始化 paginationCtrl paginationApp.controller("paginationCtrl",["$scope","$http", function($scope,$http){ $http({ method:'GET', url:'6_2.json', params:{ } }).success(function(data,status,headers,config){ //把接收到的 products 数据赋值给 products $scope.products= data.products; $scope.totalCount = data.totalCount; $scope.totalPages=Math.ceil($scope.totalCount/$scope.pageSize); for(var i=0; i<$scope.totalPages ; i++){ $scope.pageList.push(i); } }).error(function(data,status,headers,config){ alert("出错了,请联系管理员"); }); } ]); </script>
分页实例:
AngularJS实现显示10个分页按钮,当前页居中格式(左5右4):
1、思路分析:首先得到当前页 currentPage, 然后找到起始页 begin = currentPage-5; 但是这样计算会导致begin<1 所以要做一个修正判断: if(begin<1){begin=1;}
得到了begin 就可以得到: end=begin+9; 但是这样计算还有可能导致end>totalPages 所以要做一个修正判断: if(end>totalPages){end=totalpages;} ,
这意味着:end 越界了,所以end变小了,这样导致总页数没法保证10页了,所以要修正一下: begin=end-9; 当然还是要判断修正begin,防止越界:if(begin<1){begin=1;}
2、代码如下:
//加载指定页码数据 $scope.selectPage=function(page){ //校验数据,当数据越界时不进行处理 if(page<1){ return; } if($scope.totalPages!=0 && page>$scope.totalPages){ return; } //根据页码发送ajax请求获得数据 $scope.currentPage=page; $http({ method:'GET', url:'6_2.json', params:{ "page":$scope.currentPage, "rows":$scope.pageSize } }).success(function(data,status,headers,config){ //把接收到的 products 数据赋值给 products $scope.products= data.products; $scope.totalCount = data.totalCount; $scope.totalPages=Math.ceil($scope.totalCount/$scope.pageSize); //仿百度显示方式生成分页条: //1.首先确定起始页 var begin = page-5; //2.判断修正起始页 if(begin<1){ begin=1; } //3.根据第一页获得最后一页 var end = begin+9; //4.判断修正最后一页 if(end>$scope.totalPages){ end=$scope.totalPages; //一旦需要修正,那么起始页也要修正 begin=end-9; if(begin<1){ begin=1; } } alert("begin: "+begin); alert("end: "+end); // 将页码加入 PageList集合 var count=end-begin; for(var i=0;i<=count;i++){ $scope.pageList[i] = begin+i; } alert($scope.pageList[0]) }).error(function(data,status,headers,config){ alert("警告","出错了,请联系管理员","warning"); }); }
以上就是angularjs是怎么实现分页的?的详细内容,更多请关注0133技术站其它相关文章!