Skip to content

Instantly share code, notes, and snippets.

@hussaintamboli
Last active August 29, 2015 14:23
Show Gist options
  • Save hussaintamboli/9dea7af3d6694ae0ae28 to your computer and use it in GitHub Desktop.
Save hussaintamboli/9dea7af3d6694ae0ae28 to your computer and use it in GitHub Desktop.
A paginate filter in angularjs for maintaining pagination window with current page in the middle
.filter('paginate', function() {
return function(arr, page, END, START, WINDOW) {
if (typeof(START)==='undefined') START = 0;
if (typeof(WINDOW)==='undefined') WINDOW = 5;
var start = Math.floor(page - WINDOW/2);
var end = Math.floor(page + WINDOW/2);
if (start >= START && end <= END) {
return (arr || []).slice(start, end);
}
if (start <= START) {
start = START;
end = START + WINDOW;
} else {
if (end >= END) {
start = END - WINDOW;
end = END;
}
}
return (arr || []).slice(start, end);
}
});
// Usage
<!-- PAGINATION START -->
<nav class="center-block pagination-nav">
<ul class="pagination">
<li ng-class="{disabled: pagination.page == 1}">
<a aria-label="First" ng-click="setPage(1)">&laquo;</a>
</li>
<li ng-class="{disabled: pagination.page == 1}">
<a aria-label="Previous" ng-click="previousPage()">&lsaquo;</a>
</li>
<li ng-repeat="n in [] | range:pagination.total_pages | paginate:(pagination.page):(pagination.total_pages)"
ng-class="{active: n == pagination.page}"
ng-click="setPage(n)">
<a ng-bind="n"></a>
</li>
<li ng-class="{disabled: pagination.page == pagination.total_pages}">
<a aria-label="Next" ng-click="nextPage()">&rsaquo;</a>
</li>
<li ng-class="{disabled: pagination.page == pagination.total_pages}">
<a aria-label="Last" ng-click="setPage(pagination.total_pages)">&raquo;</a>
</li>
</ul>
</nav>
<!-- PAGINATION END -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment