Angular.js Pagination with Bootstrap - 羡辙杂俎
2016.05.11 16:01:49
Angular.js Pagination with Bootstrap

This post introduces how to make a pagination component with Angular.js and Bootstrap.

The following shows an expected state of our pagination component.

which could be modeled into

The left part is for the starting pages, right for ending pages, and center for pages around current one.

For example, for the second page, page - 1 is the same as 1 and page is the same as 2, so we need to hide 1, 2, and ... in the left part.

In fact, this task is more difficult than one might imagine, since there are many possible situations of our pagination. And this post is going to talk about how to make it.


In Angular controller, we define the page data, which could be replaced by backend data.

    .controller('PageController', function() {
        var vm = this;
        vm.page = {
            page: 5,
            total: 20


In HTML, we use ng-if to hide unnecessary tags, and ng-class to add class conditionally.

<ul class="pagination">
    <li ng-class="{true:'disabled'}[vm.page.page === 1]">
        <a href="#">&laquo;</a>
    <li ng-if="vm.page.page-1>1">
        <a href="#">1a</a>
    <li ng-if="vm.page.page-1>2">
        <a href="#">2b</a>

    <li ng-if="vm.page.page-1>2+1">
    <li ng-if="vm.page.page>1">
        <a href="#">{{ vm.page.page - 1 }}c</a>
    <li class="active">
        <a href="#">{{ vm.page.page }}d</a>
    <li ng-if="vm.page.page<vm.page.total">
        <a href="#">{{ vm.page.page + 1 }}e</a>
    <li ng-if="vm.page.page+1<vm.page.total-1-1">

        <a href="#" ng-if="vm.page.page+1<vm.page.total-1">{{ vm.page.total - 1 }}f</a>
        <a href="#" ng-if="vm.page.page+1<vm.page.total">{{ vm.page.total }}g</a>
    <li ng-class="{true:'disabled'}[vm.page.page === vm.page.total]">
        <a href="#">&raquo;</a>

I added abcd..g at the end for you to understand better.

Here is the pagination for varied pages.



Creative Commons License
Every blog post in this site by Wenli Zhang is licensed under a CC 3.0 License, based on a work at Github. You can see the source code of this blog site at github.com/Ovilia/blog.


comments powered by Disqus