Last active
April 7, 2016 01:49
-
-
Save jrobinsonc/8d9f5e4a5f858d8d24ddbec89c7949e4 to your computer and use it in GitHub Desktop.
Angular directive: pagination with bootstrap.
This file contains hidden or 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
| 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); | |
| } | |
| }; | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment