7/14/15

AngularJS Data Grid with Paging

With AngularJS, we can easily display a data grid with some data by just binding a JSON model to a view. In cases where the data is somewhat large, we would like to provide users with a much better experience by adding paging to the grid.  We should note that the purpose of this article is to show a technique for client side paging. For much larger data sets, this approach may not be recommended.

With AngularJS, paging can be done with the use of a custom filter and service. The filter enable us to control the data (subset) that should be displayed on each page. The service is used by the controller to manage the paging commands like previous, next and to update the model that is used by the filter to know when to show a corresponding set of data based on the current page selection. We should take a look at the following code snippet and result to see how things work, and we can then cover the details of the implementation.



As we can see in the result tab, as we press the paging buttons the grid displays only the records for the selected page (shown on the footer).  We can also change the default page size from the select box and either select 5 or 10.  Let’s cover the implementation in more detail.

Filter:

The filter basically just slices the array to return a subset of data for the selected page. The filter is placed on the ng-repeat mark-up and takes three parameters (items : data, page: current page, onPage: page size).

Service:

The service provides the model and actions that are used by the user interface elements. It is injected into the controller (app.grid) to make it available to the mark-up. This is what allows the user to page through the data and reset the page size setting. It also provides pager status like current page, number of pages and total number of records. On the controller, we set a reference of the service (ctrl.pager).

The View:

On the view, we access the paging service using the ctrl.pager property of the controller. This exposes the properties and methods of the paging service. Review the HTML tab and take a look at the HTML mark-up to see how this is done.

How this works:

As the user interacts with the paging elements (page size, previous and next buttons), the properties of the service are updated. This causes the filter (ng-repeat directive) to update again with the new paging values which can be a page changed or page size changed.


I hope this is able to show how simple paging can be implemented as a reusable service that can be injected into controllers.

0 comments :

Post a Comment

What do you think?