Skip to content

Instantly share code, notes, and snippets.

@bign8
Last active August 29, 2015 13:57
Show Gist options
  • Save bign8/9836896 to your computer and use it in GitHub Desktop.
Save bign8/9836896 to your computer and use it in GitHub Desktop.
Angular Pagination Stuff
angular.module('app', []).
controller('ctrl', ['$scope', function ($scope) {
$scope.pages = function () {
return Math.ceil( $scope.filtered_users.length / $scope.limit ) || 1;
};
}]).
filter('pagination', function () {
return function (inputArray, selectedPage, pageSize) {
var start = (selectedPage-1) * pageSize;
return inputArray.slice(start, start + pageSize);
};
}).
directive('pagination', function () {
return {
restrict: 'AE',
scope: {
numPages: '=',
currentPage: '=',
maxShow: '='
},
template: '' +
'<ul class="pagination">' +
' <li ng-class="{disabled: noPrevious()}">' +
' <a ng-click="selectPage( 1 )">&laquo;</a>' +
' </li>' +
' <li ng-class="{disabled: noPrevious()}">' +
' <a ng-click="selectPrevious()">&lsaquo;</a>' +
' </li>' +
' <li ng-repeat="page in print_pages" ng-class="{active: isActive(page)}">' +
' <a ng-click="selectPage(page)">{{page}}</a>' +
' </li>' +
' <li ng-class="{disabled: noNext()}">' +
' <a ng-click="selectNext()">&rsaquo;</a>' +
' </li>' +
' <li ng-class="{disabled: noNext()}">' +
' <a ng-click="selectPage( numPages )">&raquo;</a>' +
' </li>' +
'</ul>',
replace: true,
link: function ($scope) {
// thanks: https://github.com/angular-ui/bootstrap/blob/master/src/pagination/pagination.js#L134
var trim_pager = function () {
var startPage = Math.max($scope.currentPage - Math.floor($scope.maxShow/2), 1);
var endPage = Math.min(startPage + $scope.maxShow - 1, $scope.numPages);
if (endPage >= $scope.numPages) startPage = endPage - $scope.maxShow + 1; // adjust if necessary
$scope.print_pages = $scope.pages.slice(startPage-1, endPage);
};
$scope.$watch('numPages', function (value) {
$scope.pages = [];
for (var i = 1; i <= value; i++) $scope.pages.push(i);
if ( $scope.currentPage > value ) $scope.selectPage(value);
trim_pager();
});
$scope.$watch('currentPage', trim_pager);
$scope.noPrevious = function () {
return $scope.currentPage === 1;
};
$scope.noNext = function () {
return $scope.currentPage === $scope.numPages;
};
$scope.isActive = function (page) {
return $scope.currentPage === page;
};
$scope.selectPage = function (page) {
if ( !$scope.isActive(page) ) $scope.currentPage = page;
};
$scope.selectNext = function () {
if ( !$scope.noNext() ) $scope.selectPage( $scope.currentPage + 1 );
};
$scope.selectPrevious = function () {
if ( !$scope.noPrevious() ) $scope.selectPage( $scope.currentPage - 1 );
};
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment