TheLimeTrees
TheLimeTrees

Reputation: 411

How to add alphabetical column sorting to a table using AngularJS

Essentially I need to add a little button or something within the headers of the table to be able to sort the data alphabetically by column. I've been having trouble with doing this making use of AngularJS and need some help with it.

This is a snippet showing the table and...

<div class="col-md-10">
    <table class="table table-hover table-bordered">
        <thead>
        <tr>
            <th>Status</th>
            <th>Ref</th>
            <th>Service</th>
            <th>Domain</th>
            <th>Service Owner</th>
            <th>Stage</th>
        </tr>
        </thead>

        <tbody>
        <tr ng-click="isCollapsed = !isCollapsed" ng-repeat-start="x in projects | filter:query | filter:myFilter | orderBy:orderProp">
            <td><b>{{x.a}}</b></td>
            <td>{{x.b}}</td>
            <td><u>{{x.c}}</u></td>
            <td>{{x.d}}</td>
            <td>{{x.e}}</td>
            <td>{{x.f}}</td>
        </tr>
        <tr collapse="isCollapsed" ng-repeat-end="">
        <td colspan="6">
          <h3>Test</h3>
          <p>Test</p>
        </td>
      </tr>
        </tbody>
    </table>
    </div>
</div>

This is a plnkr of the code http://plnkr.co/edit/OkRbR9geeOcCGy2K01jB?p=preview

Upvotes: 2

Views: 2195

Answers (1)

bm1729
bm1729

Reputation: 2375

Give this a try for a very simple solution:

HTML:

<table>
    <thead>
    <tr>
        <th>Status<a ng-click="orderProperty = 'a'">^</a></th>
        <th>Ref<a ng-click="orderProperty = 'b'">^</a></th>
        <th>Service<a ng-click="orderProperty = 'c'">^</a></th>
        <th>Domain<a ng-click="orderProperty = 'd'">^</a></th>
        <th>Service Owner<a ng-click="orderProperty = 'e'">^</a></th>
        <th>Stage<a ng-click="orderProperty = 'f'">^</a></th>
    </tr>
    </thead>
    <tbody>
        <tr ng-repeat="x in projects | orderBy:orderProperty">
            <td><b>{{x.a}}</b></td>
            <td>{{x.b}}</td>
            <td>{{x.c}}</td>
            <td>{{x.d}}</td>
            <td>{{x.e}}</td>
            <td>{{x.f}}</td>
        </tr>
    </tbody>
</table>

JavaScript:

app.controller('controller', function($scope) {
    $scope.orderProperty = "f"; // Sort by "f" by default
    $scope.projects = [...];
});

Working jsFiddle here: http://jsfiddle.net/ben1729/3nxykbhk/

Upvotes: 3

Related Questions