在编写普通网页或者 web 应用时, 一个最普遍的需求就是创建分页. 分页这个词乍一听上去可能有些陌生, 但是你肯定每天都在用, 它就是你在浏览新闻时最下边显示你已经看到第几页, 同时跳转到具体某一页, 首页或者末页的那个东西.
这个当然不是什么很难的需求, 实现它的方式多种多样, 从前端到后端都可以有具体的实现方法.
下面我们来看一下 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");
- });
- }
来源: http://www.css88.com/qa/angular-js/12014.html