Skip to content

Instantly share code, notes, and snippets.

@JonCatmull
Last active February 17, 2016 10:35
Show Gist options
  • Save JonCatmull/6bf200afa114a6aec63b to your computer and use it in GitHub Desktop.
Save JonCatmull/6bf200afa114a6aec63b to your computer and use it in GitHub Desktop.
Angular directive to generate pagination numbers. Allows setting of max numbers to display and it will keep the first and last page visible.
(function() {
'use strict';
angular
.module('fcp')
.directive('pagination', pagination);
/** @ngInject */
function pagination() {
var directive = {
restrict: 'E',
scope: {
pageIndex: '=',
maxPages: '=',
totalPages: '=',
curPage: '=',
pagiMode: '@'
},
templateUrl: 'app/templates/components/pagination/pagination.html',
controller: PaginationController
};
return directive;
/** @ngInject */
function PaginationController($scope, $log, Manufacturer) {
$scope.getCurPage = function() {
if ($scope.pagiMode == 'compact') {
return $scope.pageIndex + 1;
} else {
return $scope.curPage;
}
};
$scope.setPage = function(page) {
if ($scope.pagiMode == 'compact') {
$scope.pageIndex = page - 1;
} else {
$scope.curPage = page;
}
$scope.$emit('pageChanged');
};
$scope.prevPage = function () {
if ($scope.getCurPage() > 1) {
$scope.setPage($scope.getCurPage()-1);
}
};
$scope.nextPage = function () {
if ($scope.getCurPage() < $scope.totalPages) {
$scope.setPage($scope.getCurPage()+1);
}
};
$scope.numbers = function() {
var numbers = [];
var range = Math.floor($scope.maxPages/2),
unusedDownRange = ($scope.getCurPage() < range) ? range - $scope.getCurPage() : 0,
unusedUpRange = ($scope.getCurPage() > ($scope.totalPages - range)) ? $scope.getCurPage() - ($scope.totalPages - range) : 0;
if ($scope.getCurPage() <= range) {
unusedDownRange++;
}
for(var page = 1; page <= $scope.totalPages; page++){
if (
page == 1 ||
page == $scope.totalPages ||
( page >= $scope.getCurPage() - (range - 1) - unusedUpRange &&
page <= $scope.getCurPage() + (range - 1) + unusedDownRange
)
) {
numbers.push(page);
}
}
return numbers;
};
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment