Angular2的分页组件实现

先来看看AngularJs中的分页实现:

angular.module('pagination', [])
.directive('pagination', function() {
    return {
        restrict: 'EA',
        template : '<nav>' +
                        '<ul class="pagination">' +
                            '<li ng-class="{disabled:conf.currentPage === 1}"><a href="javascript:void(0);" ng-click="prePage()" aria-label="Previous">' +
                                    '<span aria-hidden="true">上一页</span></a></li>' +
                            '<li ng-repeat="item in pageList track by $index" ng-class="{active:item === conf.currentPage}">' +
                                    '<a href="javascript:void(0);" ng-click="changeCurrentPage(item)">{{item}}</a></li>' +
                            '<li ng-class="{disabled:conf.currentPage === pageNum}"><a href="javascript:void(0);" ng-click="nextPage()" aria-label="Next">' +
                                    '<span aria-hidden="true">下一页</span></a></li>' +
                        '</ul>' +
                    '</nav>',
        replace: true,
        scope: {
            conf: '='
        },
        link: function(scope, element, attrs) {
            //分页显示长度(显示页码数,必须是奇数)
            var pageLength = 7;
            //改变当前页
            scope.changeCurrentPage = function(item){
                if(item == '...'){
                    return;
                }else{
                    scope.conf.currentPage = item;
                    if(scope.conf.changePage){
                        scope.conf.changePage();
                    }
                }
            };
            //前一页
            scope.prePage = function(){
                if(scope.conf.currentPage === 1){
                    return ;
                }
                scope.changeCurrentPage(scope.conf.currentPage - 1);
            };
            //后一页
            scope.nextPage = function(){
                if(scope.conf.currentPage === scope.pageNum){
                    return ;
                }
                scope.changeCurrentPage(scope.conf.currentPage + 1);
            };
            //偏移量(因为要除去首页和尾页,所以要-1)
            var offset = parseInt(pageLength / 2) - 1;
            function initPageList(){
                //如果没有数据显示一页
                scope.conf.totalItems = scope.conf.totalItems > 0 ? scope.conf.totalItems : 1;
                //总页数
                scope.pageNum =  Math.ceil(scope.conf.totalItems / scope.conf.pageItems);
                scope.pageList = [];
                if(scope.pageNum <= pageLength){
                    for (var i = 1; i <= scope.pageNum ; i++) {
                        scope.pageList.push(i);
                    }
                }else{
                    //左边没有'...'
                    if(scope.conf.currentPage < pageLength - offset){
                        for (var i = 1; i < pageLength ; i++) {
                            scope.pageList.push(i);
                        }
                        scope.pageList.push('...');
                        scope.pageList.push(scope.pageNum);
                    }else if(scope.conf.currentPage >= scope.pageNum - offset - 1){
                        //右边没有'...'
                        scope.pageList.push(1);
                        scope.pageList.push('...');
                        for (var i = pageLength - 2; i >= 0; i--) {
                            scope.pageList.push(scope.pageNum - i);
                        }
                    }else{
                        //两边都有'...'
                        scope.pageList.push(1);
                        scope.pageList.push('...');
                        for(var i = scope.conf.currentPage - offset;i <= scope.conf.currentPage + offset; i++){
                            scope.pageList.push(i);
                        }
                        scope.pageList.push('...');
                        scope.pageList.push(scope.pageNum);
                    }
                }
            };

            //监听数据变化,改变分页
            scope.$watch('conf.currentPage',initPageList);
            scope.$watch('conf.totalItems',function(newVal,oldVal){
                if(newVal !== oldVal){
                    scope.conf.currentPage = 1
                    initPageList();
                }
            });
        }
    };
});

定义module时引入:

angular.module('myApp', ['pagination']);

定义分页配置对象

$scope.paginationConf = {
        currentPage: 1,
        totalItems: 0,
        pageItems: 10,
        changePage: function () {
            $scope.queryList();//翻页时候执行的方法
        }
    };

http请求查询数据封装:

$scope.queryList = function () {
        var params = {
            page: $scope.paginationConf.currentPage - 1
        };
        $http.post("/query/queryList", $.param(params)).success(function (data) {
            $scope.list = data.result.list;
            $scope.paginationConf.totalItems = data.result.totalElements;
        });
    };

页面调用:

<pagination conf="paginationConf"></pagination>

直接参照AngularJs,来看看Angular2中分页实现:

  1. 要封装组件,所以我们要创建一个分页包 pagination,然后在里面依次创建几个文件:
    page.component.html 分页组件的标签内容
    page.conponent.ts 分页组件定义
    pagination.ts 分页组件所需配置信息的对象
    index.ts 导出分页组件

2.然后看看各个文件内容

page.component.html

<nav aria-label="Page navigation" style="float: right">
  <ul class="pagination">
    <li class="page-item" [ngClass]="{disabled:pagination.currentPage === 1}">
      <a class="page-link" href="javascript:void(0);" (click)="prePage()" aria-label="Previous">
        <span aria-hidden="true">上一页</span>
      </a>
    </li>
    <li class="page-item" *ngFor="let item of pageList;trackBy:index" [ngClass]="{active:item === pagination.currentPage}">
      <a class="page-link" href="javascript:void(0);" (click)="changeCurrentPage(item)">{{item}}</a>
    </li>
    <li class="page-item" [ngClass]="{disabled:pagination.currentPage === pageNum}">
      <a class="page-link" href="javascript:void(0);" (click)="nextPage()" aria-label="Next">
        <span aria-hidden="true">下一页</span>
      </a>
    </li>
  </ul>
</nav>

page.conponent.ts

import {Component, Input, DoCheck} from "@angular/core";

import { Pagination } from "./pagination";

@Component({
  selector: 'page',
  templateUrl: "./page.component.html"
})
export class PageComponent implements DoCheck{

  @Input()
  public pagination:Pagination;

  public pageNum:number;
  public pageList:any[];

  private oldTotalItems:number = 0;

  public changeCurrentPage(item:any): void{
    if(typeof item === 'number'){
      this.pagination.currentPage = item;
      this.pagination.changePage();
    }
  }

  public prePage():void {
    if(this.pagination.currentPage != 1){
      this.changeCurrentPage(this.pagination.currentPage - 1);
    }
  }

  public nextPage():void {
    if(this.pagination.currentPage < this.pageNum){
      this.changeCurrentPage(this.pagination.currentPage + 1);
    }
  }

  public initPageList():void {
    //偏移量(因为要除去首页和尾页,所以要-1)
    let offset = Math.floor(this.pagination.pageLength / 2) - 1;
    //如果没有数据显示一页
    this.pagination.totalItems = this.pagination.totalItems > 0 ? this.pagination.totalItems : 1;
    //总页数
    this.pageNum = Math.ceil(this.pagination.totalItems / this.pagination.pageItems);
    this.pageList = [];
    if(this.pageNum <= this.pagination.pageLength){
      for (let i=1;i <= this.pageNum;i++){
        this.pageList.push(i);
      }
    }else {
        //左边没有'...'
      if(this.pagination.currentPage < this.pagination.pageLength - offset){
        for(let i=1;i < this.pagination.pageLength;i++){
          this.pageList.push(i);
        }
        this.pageList.push('...');
        this.pageList.push(this.pageNum);
        //右边没有'...'
      }else if(this.pagination.currentPage >= this.pageNum - offset - 1){
        this.pageList.push(1);
        this.pageList.push('...');
        for(let i=this.pagination.pageLength - 2;i >= 0 ;i--){
          this.pageList.push(this.pageNum - i);
        }
        //两边都有'...'
      }else {
        this.pageList.push(1);
        this.pageList.push('...');
        for(let i= this.pagination.currentPage - offset;i <= this.pagination.currentPage + offset; i++){
          this.pageList.push(i);
        }
        this.pageList.push('...');
        this.pageList.push(this.pageNum);
      }
    }
  }

  ngDoCheck():void {
    if(this.pagination.totalItems != this.oldTotalItems){
      this.initPageList();
      this.oldTotalItems = this.pagination.totalItems;
    }

    if(this.pagination.currentPage > this.pageNum){
      this.pagination.currentPage = this.pageNum;
      this.pagination.changePage();
    }
  }

}

pagination.ts


export class Pagination {

  /**
   * 构造函数,同时设置属性,初始值
   * @param pageLength 显示的页码数,奇数,默认7
   * @param currentPage 当前页码数,默认1
   * @param totalItems 总条数 默认0
   * @param pageItems 每页显示条数,默认10
   * @param changePage 翻页时调用的方法
   */
  constructor(
    public pageLength:number = 7,
    public currentPage:number = 1,
    public totalItems:number = 0,
    public pageItems:number = 10,
    public changePage:() => void
  ){}

  public static defaultPagination = new Pagination(7,1,0,10, function () {});
}

index.ts

export * from './page.component';

3.使用分页组件

  • app.module.ts 的declarations加入分页组件
  • 页面调用 < page [(pagination)]=”pagination” > < / page>
  • 引入分页对象,并初始化配置
    @Output()
    public pagination:Pagination = Pagination.defaultPagination;

最后就在初始化调用了

  public ngOnInit() :void {
    this.initList();
    this.pagination.changePage = (() => {
      this.initList();
    });
  }

  private initList(): void {
    let url:string ='your-url';
    let page = this.pagination.currentPage - 1;
    this.http.get(url + "?page=" + page)
      .toPromise()
      .then(response => response.json())
      .then(page => {
        this.pagination.totalItems = page.totalElements;
        this.content = page.content;
      })
      .catch(this.handleError);
  }

当然可以封装到公司的私库中,或者对分页组件按照自己的需要进行进一步的封装调整,以后直接引入即可。

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值