Skip to content

Instantly share code, notes, and snippets.

@cbankston
Created January 27, 2016 15:50
Show Gist options
  • Save cbankston/85d2cc9d5001584cf903 to your computer and use it in GitHub Desktop.
Save cbankston/85d2cc9d5001584cf903 to your computer and use it in GitHub Desktop.
angular pagination directive
(function() {
'use strict';
angular.module('blocks.pagination', []);
})();
.container
.row
.col-md-4
span {{ vm.total }} total
.col-md-8.clearfix
ul.pagination.right
li(ng-class="{'disabled' : vm.isCurrentPage(vm.config.first)}")
a(ng-click="vm.gotoPage(vm.config.first)") First
li(ng-class="{'disabled' : vm.isCurrentPage(vm.config.prev)}")
a(ng-click="vm.gotoPage(vm.config.prev)") «
li(ng-class="{'active' : vm.isCurrentPage(page)}", ng-repeat="page in vm.config.between")
a(ng-click="vm.gotoPage(page)") {{ page }}
li(ng-class="{'disabled' : vm.isCurrentPage(vm.config.next)}")
a(ng-click="vm.gotoPage(vm.config.next)") »
li(ng-class="{'disabled' : vm.isCurrentPage(vm.config.last)}")
a(ng-click="vm.gotoPage(vm.config.last)") Last
(function() {
'use strict';
angular
.module('blocks.pagination')
.directive('pagination', Pagination);
Pagination.$inject = [];
function Pagination(){
return {
bindToController: true,
controller: 'PaginationCtrl',
controllerAs: 'vm',
templateUrl: 'views/blocks/pagination/pagination.html',
restrict: 'E',
replace: true,
scope: {
page: '=',
total: '='
}
};
}
})();
(function(math) {
'use strict';
angular
.module('blocks.pagination')
.controller('PaginationCtrl', PaginationCtrl);
PaginationCtrl.$inject = ['$location', '$scope'];
function PaginationCtrl($location, $scope){
var vm = this;
vm.config = {};
vm.gotoPage = gotoPage;
vm.isCurrentPage = isCurrentPage;
vm.limit = 200;
$scope.$watch(function() {
return vm.total;
}, buildConfig);
function buildConfig() {
vm.config['current'] = vm.page;
vm.config['first'] = 1;
vm.config['last'] = math.ceil((vm.total || 1) / vm.limit);
if (vm.page >= vm.config['last']) {
vm.config['next'] = vm.config['last'];
} else {
vm.config['next'] = (vm.page - 0) + 1;
}
if (vm.page <= 1) {
vm.config['prev'] = 1;
} else {
vm.config['prev'] = vm.page - 1;
}
vm.config['between'] = buildBetween();
}
function buildBetween(total) {
var total = total || 7;
var middle = Math.floor(total / 2);
var start = vm.page - middle;
if (start < 1) {
start = 1;
}
var end = start + total - 1;
if (end > vm.config['last']) {
end = vm.config['last'];
if ((end - start) < total) {
// recalculate start
start = end - total + 1;
if (start < 1) {
start = 1;
}
}
}
var pages = [];
for (var i = start; i <= end; i++) {
pages.push(i);
}
return pages;
}
function gotoPage(page) {
if (page == 1) {
page = null;
}
$location.search({ page: page });
}
function isCurrentPage(page) {
return vm.page == page;
}
}
})(Math);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment