angular pagination service
半年多前写的一个 angular pagination service 整合到这里。
所需要的依赖是 angular 1.2 +
控件支持基本功能 prev(上一页),next(下一页),跳转至某一页(loadPage) 等方法
控件调用方式采用实例化(new Pagination(totalCount,opts))的方式进行初始化调用, 构造方法需要两个参数totalCount 和opts ;
第一个参数totalCount 页面需要展示数据的总条数。
第二个参数是一个参数集对象,下面解释了每个参数的具体意义
1 opts: { 2 //当前页下标 3 currentPage: 1, 4 5 //分页总页数,是根据数据的行数除以每页的数量来计算出的 6 totalPage: 1, 7 8 //每页展示的行数, 9 pageSize: 10, 10 11 12 //当前选中的页码Index 13 currSelectedPage: 1, 14 15 //控件最大展示页码数量 16 visiblePages: 7, 17 18 //渲染列表数据的回调方法,既点击页面后的页面数据请求方法。 19 //每次控件页码被点击时,该方法会被调用,以便控件调用者请求相应页码的数据。 20 //@param {SelectedPageIndex} 该方法执行同时会传递被点击的页码的index作为参数 21 renderData: function(SelectedPageIndex) { 22 return false; 23 }
对于如何使用的话非常方便,只需要在controller中添加相关依赖后,实例化后调用load方法加载。
相关service代码如下
angular.module('customPagination', []).
customPagination.factory('Pagination', function () {
/**
* constructor
* @param {Number} total The total data row counts
* @param {Object} pagination Several parameters for paging range or limit etc.. this can be over write and append more custom params inside. For details, see property 'opts' of Pagination.
*/
function Pagination(total, pagination) {
this.total = (!total || total < 0) ? 1 : total;
angular.extend(this.opts, pagination || {});
}
Pagination.prototype = {
//Initialize options with default values
opts: {
//Current page index
currentPage: 1,
//Total page numbers which catulated by total and pageSize
totalPage: 1,
//Rows in every page
pageSize: 10,
//Current selected page index
currSelectedPage: 1,
//maxmium page number
visiblePages: 7,
//callback function, invokes while clicking page number
//@param {PageIndex} delivers the triggered page index.
renderData: function () {
return false;
}
},
load: function () {
//generate page links
var pages = [];
var opts = this.opts;
opts.totalPage = Math.ceil(this.total / opts.pageSize);
opts.endPage = opts.totalPage;
var half = Math.floor(opts.visiblePages / 2);
var start = opts.currentPage - half + 1 - opts.visiblePages % 2;
var end = opts.currentPage + half;
// handle boundary case
if (start <= 0) {
start = 1;
end = opts.visiblePages;
}
if (end > opts.totalPage) {
end = opts.totalPage;
}
var itPage = start;
while (itPage <= end) {
pages.push(itPage);
itPage++;
}
this.pages = pages;
opts.renderData(opts.currentPage);
},
next: function () {
if (this.opts.currentPage < this.opts.totalPage) {
this.opts.currentPage++;
this.load();
}
},
prev: function () {
if (this.opts.currentPage > 1) {
this.opts.currentPage--;
this.load();
}
},
loadPage: function (page) {
this.opts.currentPage = page;
this.load();
},
setSelected: function (page) {
this.opts.currSelectedPage = page;
},
resetPage: function () {
this.opts.currSelectedPage = 1;
this.opts.currentPage = 1;
}
};
return Pagination;
});
demo地址 jsfiddle 包含一个directive ui(引用bootstrap.css 3.0 +)。之所以没把ui 与service 集成在一起的原因是解耦合, 这样使用者可以写针对业务的个性化ui(及其样式)

浙公网安备 33010602011771号