Angular directive: pagination with bootstrap.
angular.module("app.directives", [])
.directive("pagination", function($location){
return {
restrict: 'A',
link: function($scope, element, attrs) {
function getInt (val){
return parseInt(String(val).replace(/[^0-9]+/, ''));
}
var totalRows = getInt($scope[attrs.totalRows]),
perPage = getInt($scope[attrs.perPage]),
queryString = $location.search();
if (totalRows === 0 || perPage === 0)
return;
if ("per_page" in queryString){
perPage = getInt(queryString.per_page);
}
var $ele = $(element),
numPages = Math.ceil(totalRows / perPage),
html = '',
currentPage = "pag" in queryString? parseInt(queryString.pag) : 1;
if (currentPage < 1){
currentPage = 1;
queryString.pag = currentPage;
$location.search(queryString);
}
if (currentPage > numPages){
currentPage = numPages;
queryString.pag = currentPage;
$location.search(queryString);
}
attrs.baseUrl = attrs.baseUrl + "&per_page=" + perPage;
html += '<ul class="pagination">';
html += '<li class="'+ (currentPage === 1? 'disabled' : '') +'">';
html += '<a href="#'+ attrs.baseUrl +'&pag='+ (currentPage-1) +'" aria-label="Previous"><span aria-hidden="true">«</span></a>';
html += '</li>';
for (var i = 1; i <= numPages; i++) {
html += '<li class="'+ (currentPage === i? 'active' : '') +'">';
html += '<a href="#'+ attrs.baseUrl +'&pag='+ i +'">'+ i +'</a>';
html += '</li>';
}
html += '<li class="'+ (currentPage === numPages? 'disabled' : '') +'">';
html += '<a href="#'+ attrs.baseUrl +'&pag='+ (currentPage+1) +'" aria-label="Next"><span aria-hidden="true">»</span></a>';
html += '</li>';
html += '</ul>';
$ele.html(html);
}
};
});