116 lines
2.3 KiB
JavaScript
116 lines
2.3 KiB
JavaScript
|
angular.module('MyApp')
|
||
|
|
||
|
.directive('pagination', function ($parse) {
|
||
|
var util = {}
|
||
|
var directive = {}
|
||
|
|
||
|
directive.restrict = 'A'
|
||
|
directive.scope = true
|
||
|
directive.link = function (scope, element, attrs) {
|
||
|
scope.pages = []
|
||
|
if (scope.pagination == null)
|
||
|
scope.pagination = {}
|
||
|
|
||
|
var params = scope.pagination
|
||
|
|
||
|
if (params.page == null)
|
||
|
params.page = util.init.page
|
||
|
if (params.limit == null)
|
||
|
params.limit = util.init.limit
|
||
|
if (params.buttons == null)
|
||
|
params.buttons = util.init.buttons
|
||
|
|
||
|
var recalc = function() {
|
||
|
scope.pages = util.calculate(params);
|
||
|
}
|
||
|
|
||
|
scope.$watch('pagination.total', recalc);
|
||
|
scope.$watch('pagination.page', recalc);
|
||
|
scope.$watch('pagination.limit', recalc);
|
||
|
}
|
||
|
|
||
|
util.init = {
|
||
|
page: 1,
|
||
|
limit: 10,
|
||
|
buttons: [
|
||
|
// Arrow indices
|
||
|
{pos: 'arrows', current: 4, prev: 3, next: 5},
|
||
|
{pos: 4, diff: 0},
|
||
|
{pos: 5, diff: 1},
|
||
|
{pos: 6, diff: 2},
|
||
|
{pos: 7, diff: 5},
|
||
|
{pos: 8, diff: 'max'},
|
||
|
{pos: 3, diff: -1},
|
||
|
{pos: 2, diff: -2},
|
||
|
{pos: 1, diff: -5},
|
||
|
{pos: 0, diff: 'min'},
|
||
|
],
|
||
|
}
|
||
|
|
||
|
util.clamp = function (x, min, max) {
|
||
|
if (x < min) return min;
|
||
|
if (x > max) return max;
|
||
|
return x;
|
||
|
}
|
||
|
|
||
|
util.calculate = function (params) {
|
||
|
var result = [];
|
||
|
var pos = [];
|
||
|
|
||
|
params.buttons.forEach(function (button) {
|
||
|
if (button.pos === 'arrows') {
|
||
|
result.current = button.current
|
||
|
result.prev = button.prev
|
||
|
result.next = button.next
|
||
|
return
|
||
|
}
|
||
|
|
||
|
var page = 0
|
||
|
|
||
|
if (button.diff === 'min')
|
||
|
page = params.min
|
||
|
else if (button.diff === 'max')
|
||
|
page = params.max
|
||
|
else
|
||
|
page = util.clamp(params.page + button.diff, params.min, params.max)
|
||
|
|
||
|
if (pos.indexOf(page) !== -1)
|
||
|
page = 'hide'
|
||
|
|
||
|
pos.push(page)
|
||
|
result[button.pos] = page
|
||
|
})
|
||
|
|
||
|
return result;
|
||
|
}
|
||
|
|
||
|
return directive
|
||
|
})
|
||
|
|
||
|
.filter('paginate', function() {
|
||
|
return function(data, params) {
|
||
|
var result = data
|
||
|
var start = 0
|
||
|
|
||
|
var limit = params.limit
|
||
|
var page = params.page
|
||
|
|
||
|
var max = Math.max(1, Math.ceil(data.length / limit))
|
||
|
var page = Math.min(page, max)
|
||
|
|
||
|
if (limit !== -1) {
|
||
|
start = (page - 1) * limit
|
||
|
result = data.slice(start, start + limit)
|
||
|
}
|
||
|
|
||
|
params.total = data.length
|
||
|
params.start = start + 1
|
||
|
params.end = start + result.length
|
||
|
params.page = page
|
||
|
params.min = 1
|
||
|
params.max = max
|
||
|
|
||
|
return result;
|
||
|
};
|
||
|
})
|