如何允许对数据表进行排序?

时间:2018-12-17 19:13:21

标签: javascript angularjs

我有一个要循环输入数据的表。我想在表格标题上添加一个排序。我遵循了一个发现的示例,但它似乎无法过滤表格。

我的组件HTML:

    <h5 class="table-title">{{title}}</h5>
<table>
 <thead>
    <tr>
        <td ng-click="">Qty</td>
        <td>
            <a href="#" id="nameSort" ng-click="sortType = 'name'; sortReverse = !sortReverse">Name</a>
            <span ng-show="sortType == 'name' && !sortReverse" class="fas fa-sort-down"></span>
            <span ng-show="sortType == 'name' && sortReverse" class="fas fa-sort-up"></span>
        </td>
    </tr>
    </thead>
    <tbody>
    <tr ng-repeat="(name, available) in availability.mappables[0].availability | limitTo: 5" id="{{$index}}" ng-class="{'last': $last}">
        <td class="qty">{{available}}</td>
        <td class="item" id="{{$last}}">{{name}}</td>
    </tr>
    </tbody>
</table>

这是我的控制器的外观:

  $scope.sortType     = 'name'; // set the default sort type
$scope.sortReverse  = false;  // set the default sort order


$scope.sortBy = function(propertyName) {
    $scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;
    $scope.propertyName = propertyName;
};

2 个答案:

答案 0 :(得分:1)

看看有角度的文档中的示例

https://docs.angularjs.org/api/ng/filter/orderBy

此文档中的示例正是您想要的:

ng-repeat="friend in friends | orderBy:propertyName:reverse"

https://plnkr.co/edit/55p0yMRLnCm6twXUleHH?p=preview

答案 1 :(得分:0)

也许,您可以使用纯JavaScript代码解决此问题。看一下sort()方法。会是这样的:

    $scope.cars = [
      {type:"Volvo", year:2016},
      {type:"Saab", year:2001},
      {type:"BMW", year:2010}
    ];
    //sort direction
    let direction = true;
    function myFunction() {
    direction = !direction;
    if(direction)
      $scope.cars.sort((a, b) => {return a.year - b.year});
    else
      $scope.cars.sort((a, b) => {return a.year + b.year});
    }