JAVASCRIPT

SIMPLE PAGINATION IN ANGULARJS


Try to imagine AngularJS without the ng-repeat directive. Life would be so hard, huh? but even as easy and natural as it is to loop through a collection using the ng-repeat directive, some questions pop up.

Questions like:

  • “What if the collection I need to loop through is massive?
  • What if I only need to display a certain number of items per page?”

The only logical answer to these questions is to implement pagination.

There are several ways of implementing pagination in AngularJS. You might decide to get your hands dirty and write some code to do the trick. Before you do that, what if the AngularJS team already provided a native angular directive to handle pagination? That would have been awesome! . Sorry to break your heart…They didn’t, someone else did! .

I hereby introduce the simplest and most intuitive way of handling pagination in AngularJS: angularUtils by Michael Bromley. Below is how to implement pagination with the directive.

The first step is to get the angular module:

OR

 

You might as well just download the dirPagination.js and dirPagination.tpl.html files from GitHub.

Then include the module in your app as a Dependency

 

Once that is done, all you have to do is include a few lines of markup and code. The simplest way to do this is shown below:

First, add the directive to your HTML in place of ng-repeat:

 

One thing to note is that the directive internally delegates to ng-repeat, so you can go ahead and access each item in Items the same way you can do in ng-repeat.

Next.., In the controller that contains the Items collection, set the following scope variables

 

The currentPage variable is to specify which page the pagination should default to and the PageSize specifies how many items to display per page, which in turn affects the pagination buttons. I specified the starting page to be 1 and the number of items per page to be 5.

After all these have been set, the following should be added to the HTML file to display the pagination buttons like so:

 

One thing to note in the directive above is the “template-url” which points to the default pagination template in the downloaded module, which uses bootstrap pagination style. But the good news is that it can be customized based on the colour scheme of the application.

That is it. A working implementation of the directive can be viewed on Plunker. You can also head over to the GitHub page to get more info about the directive and more ways to customize it.

Hope this helps.

About Babatunde Mustapha