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 http://jsfiddle.net/Xanetia/Azhg7/. 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’])): http://www.mediafire.com/?96p8pk72u0h2rfr
To use this table sorting service (or in fact to sort ANY ngRepeat) you have to do the following:
- Inject MultiOrder into your controller.
- 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.
- 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).
- 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.