如何使用AngularJS向表中添加字母列排序

时间:2015-06-22 14:45:56

标签: javascript angularjs sorting

基本上我需要在表格的标题中添加一个小按钮或类似内容,以便能够按列按字母顺序对数据进行排序。我在使用AngularJS时遇到了麻烦,需要一些帮助。

这是显示表格的片段......

<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>

这是代码http://plnkr.co/edit/OkRbR9geeOcCGy2K01jB?p=preview

的plnkr

1 个答案:

答案 0 :(得分:3)

尝试一个非常简单的解决方案:

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 = [...];
});

在这里工作jsFiddle:http://jsfiddle.net/ben1729/3nxykbhk/