AngularJS Table Sort Service

I’ve been meaning to do an angular post for a while having enjoyed the framework immensely. First off, go have a look here It supports multiple direction and column (hold shift and click headers) sorting (actually on any ng-repeat, but a table is the simplest usage). Now all you have to do if you want to use it is copy the factory as in that link, or download the following file (which has a bunch of other useful directives as well) and include the ‘sdevgame’ in your module declaration (eg angular.module(‘myapp’, [‘sdevgame’])):

To use this table sorting service (or in fact to sort ANY ngRepeat) you have to do the following:

  1. Inject MultiOrder into your controller.
  2. Add ng-click=”modOrder($event, ‘name’)” where ‘name’ is the variable you want to orderBy in the ngRepeat, to the elements that you want to use for ordering. In the jsFiddle above I use the <th> tags to order each column.
  3. Add ” | orderBy: MultiOrder.orderArray” to any ngRepeats you want to order (this even works on multiple as long as the object names are the same).
  4. In your controller setup the following:
    $scope.MultiOrder = MultiOrder;
    $scope.MultiOrder.orderArray = ['-name'];//set the initial order
    $scope.MultiOrder.forceOrder = ['+name'];//set any default forced order
    $scope.MultiOrder.plusSortClass = "green";//these classes are put on the element when the sort is applied
    $scope.MultiOrder.minusSortClass = "blue";
    $scope.modOrder = MultiOrder.modOrder;

Note: I haven’t figured a way of dynamically applying the initial sorting class, so if you set the initial order or a force order don’t forget to add the class to the relative order element.

About Simeon Cheeseman

I enjoy a wide variety of computer and board games, have a BSc in Computer Science and have played percussion for 18 years.

Posted on July 24, 2012, in AngularJS, HTML, Javascript and tagged , , . Bookmark the permalink. 2 Comments.

  1. Mikael Jagekrans

    Big thanks, you just saved me a couple of days work!

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

%d bloggers like this: