Client side Pagination through Custom Angular JS Filter

Angular JS is a powerful front-end framework and often I have tried and successfully delegated it responsibilities for which I might have written a good chunk of code on the server back-end. One such instance was pagination. If you are not familiar, pagination is a technique through which we present tabular data to the user by breaking it into pages.

In one of my projects, I encountered a use-case in which the size of the records coming in was not very very huge. I wanted to paginate the records to enhance the user experience and making round trips to the server to fetch each page felt like forever. It is then I decided to completely handover my pagination responsibilities to the front-end.

I could have done everything I needed to paginate the records on the controller with Loadash doing all the heavy lifting and filtering for me, but I felt guilty. It felt like treason to write something that “un-re-useable”. Beautiful software is not complex, it is simple.  So, I wanted to create a custom filter in Angular JS which would filter out the records for me and all I needed to do was to give it suitable parameters through my view. And then I can use the “all-famous” UI-Bootstrap controls for pagination to show the user what page are you on, how many pages are there altogether etc.

The bird’s eye view of the filter function was:

Input: 1) Complete list of records, 2) Requested page number (we will call this current page) and 3) Records per page

Output: List of records for the requested page

Here is how simple and tiny the filter came out to be …

Its usage is even simpler.

Hook it up as a filter to the ng-repeat expression as follows and it would to all the pagination stuff for you.

— Look for hints in the comments

Pretty simple huh ?

Its complete source can be found in this little github repository. Just clone the it and open up “index.html” and browse to the pagination demo.

It’s good, isn’t it ? — Big Boss


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s