Last active
February 17, 2016 10:35
-
-
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.
This file contains 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
(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