Created
February 20, 2016 15:16
-
-
Save think2011/678d1119d5344f2666a3 to your computer and use it in GitHub Desktop.
生成用于angular的分页组件的对象结构
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default angular.module('dtcloud.directive.pager', []) | |
.factory('Pager', PagerFactory) | |
.directive('pager', PagerDirective) | |
/** | |
* 生成一个适用于 PagerDirective 的对象结构 | |
* @returns {Pager} | |
* @constructor | |
*/ | |
function PagerFactory() { | |
return class Pager { | |
/** | |
* @param options | |
* @param options.fetchFn {function} 用于查询的函数,这个函数必须返回promise, promise返回的data必须是total(分页总条目数) | |
* @param [options.params] {object} 每次都会更新 fetchFn 的查询参数 | |
* @param [options.loading] {boolean} 加载状态 | |
* @param [options.total] {number} 分页总条目数 | |
* @param [options.currentPage] {number} 当前页 | |
* @param [options.maxSize] {number} 页码限制 | |
* @param [options.currentPageKey] {string} params中对应的当前页的key | |
* @param [options.maxSizeKey] {string} params中对应的页码限制的key | |
*/ | |
constructor(options) { | |
Object.assign(this, { | |
loading: false, | |
params: {}, | |
total: 0, | |
currentPage: 1, | |
maxSize: 10, | |
currentPageKey: 'start', | |
maxSizeKey: 'limit', | |
}, options); | |
} | |
/** | |
* 获取数据 | |
* @param params | |
* @returns {*} | |
*/ | |
fetch(params) { | |
if (this.loading) return; | |
this.loading = true; | |
this.params = params; | |
return this.fetchFn(params) | |
.then(total => { | |
this.currentPage = params[this.currentPageKey]; | |
this.maxSize = params[this.maxSizeKey]; | |
this.total = total; | |
}) | |
.finally(() => { | |
this.loading = false; | |
}); | |
} | |
} | |
} | |
/** | |
* 根据业务封装的分页器 | |
* | |
* @restrict EA | |
* @scope | |
* @param handle {object} 通过 PagerFactory 构造的对象结构 | |
* | |
* @requires PagerFactory | |
* | |
*/ | |
function PagerDirective() { | |
'ngInject'; | |
let template = ` | |
<nav> | |
<uib-pagination | |
force-ellipses="true" | |
ng-change="change()" | |
ng-disabled="handle.loading" | |
total-items="handle.total" | |
max-size="maxSize" | |
ng-model="currentPage" | |
class="pagination-sm" | |
previous-text="«" | |
next-text="»"> | |
</uib-pagination> | |
</nav> | |
`; | |
return { | |
restrict: 'EA', | |
replace: true, | |
scope: { | |
handle: '=' | |
}, | |
template: template, | |
link: linkFunc | |
} | |
function linkFunc(scope, elem, attr, ctrl) { | |
let handle = scope.handle; | |
scope.maxSize = handle.maxSize; | |
scope.currentPage = handle.currentPage; | |
scope.change = () => { | |
handle.params[handle.currentPageKey] = scope.currentPage; | |
handle.fetch(handle.params); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment