Friday, May 16, 2014

Build the perfect Angularjs Grid

I my first post i'll show you how to build your own Angularjs data grid.

In this post, I wont build an all-to-do directive (kind of do all the dirty work for us : generate markup and wire all together). I think it's not a good idea, ad-hoc directives offer quick and easy solutions for your starting use case. However, once you start to look after your special needs, you reach the limits.

I like to have all the flexibility to compose my template and wire things with behaviors and this the approach i'll take here.

we'll incrementally build behaviors and see how to exploit them in our templates. this way you'll learn how to solve even the most complex Use Cases by mean of 'compose and bind'.

so enough talking and let's begin.

1- Obliged 'Hello Grid' :


Let's start with the simplest use case, we want to show the user a list of data objects


So this is a basic ng-repeat loop, nothing magic.

2- Make it more generic:


In order to make column generation dynamic, we will move the columns definition into the controller. Then we can bind to them from our template.
Now, we have a grid that can show data from any object, not just phones.

3- Sorting

We will make this in 2 steps

a- first implement the feature directly in the code:


First, we will add all the required code in the controller
In this step, we added three properties to our controller:
  1. a sort object to remember the sorted column and the sort direction ('+' or '-')
  2. a function to calculate the exrpression nedded by the 'orderBy' filter : ie '+id' to apply an ascendant sort in the 'id' property (see orderBy filter documention)
  3. and finally a 'toggleSort' function: it will be called when the user clicks on the header
All we have to do is to bind to this in our template

b- Now, we can refactor that into a nice directive:


In order to get a more generic sort feature, we will add a 'sort-by' directive; typically you use multiples sort-by directives so we need to share the sort object ({ column: ..., direction: ...}) between the multiples sort-by directives; for that we wille use a 'wrapper' directive 'sort-group' in order to provide a binding for the child directives


Access the full working example in Plunker.


That's it; in the next post w'll see about filtering.

No comments:

Post a Comment