AngularJS - 单击列时对数据进行升序/降序排序

时间:2017-12-07 14:43:13

标签: javascript angularjs sorting

我有以下视图代码:

<tr ng-repeat="c in clients | orderBy:'code'">
    <td>{{c.firstname}} {{c.lastname}}</td>
    <td>{{c.telephone}}</td>
    <td>{{c.location}}</td>
    <td>{{c.code}}</td>
</tr>

我想在点击列时更改orderBy:'code',假设用户点击了列位置,我希望orderBy条件更改为&#39; location&#39;代替代码,并采用这种形式

<tr ng-repeat="c in clients | orderBy:'location'">

3 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

写入 - 点击列并调用类似setSortByParameter的函数并设置字段sortBy。

现在编写orderBy,如下所示。

<tr ng-repeat="c in clients | orderBy:'{{sortBy}}'">

答案 2 :(得分:0)

&#13;
&#13;
angular.module('app', []).controller('ctrl', function($scope) {
  $scope.prefix = '+';
  $scope.sort = '';
  $scope.sortFn = function(name) {
    $scope.prefix = $scope.prefix == '-' ? '+' : '-';
    $scope.sort = $scope.prefix + name;
  }
  $scope.arrow = function(name){
    if($scope.sort.indexOf(name) != -1)
      return $scope.prefix == '+' ? '↑' : '↓';
    return '';
  }

  $scope.clients = [
    { name: 'Tom', age: 30 },
    { name: 'Max', age: 20 },
    { name: 'Sam', age: 40 },
    { name: 'Liza', age: 25 },
    { name: 'Henry', age: 35 }
  ]
})
&#13;
table,
th,
td {
  border: 1px solid black;
  border-collapse: collapse;
}
th{
  cursor: pointer
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<table ng-app='app' ng-controller='ctrl'>
  <thead>
    <tr>      
      <th ng-click='sortFn("name")'>Name {{arrow("name")}}</th>
      <th ng-click='sortFn("age")'>Age {{arrow("age")}}</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="c in clients | orderBy:sort">
      <td>{{c.name}}</td>
      <td>{{c.age}}</td>
    </tr>
  </tbody>
</table>
&#13;
&#13;
&#13;