AngularJs orderby过滤器没有正确排序数据

时间:2016-04-25 11:20:40

标签: javascript angularjs

我使用控制器中的ng-repeat在html中显示了一组客户。

这里我尝试使用orderby过滤器对数据进行排序。但问题是当数组初始化时,它按升序顺序正确排序。但是,当我单击Name标题时,它会对数据进行切换,但不会按预期下降数据。这是一个运行的plunker:

http://plnkr.co/4aAH08bzVUnws5RRx5RP

AngularJs:

app.controller('MainCtrl', function($scope) {

  $scope.sortIt = "name";
  $scope.reverse = false;

  $scope.customers = [
                            {
                                name:'AAA',
                                city: 'Dublin',
                                orderTotal: 9.9563,
                                joined: '1947-10-10'},
                            {
                                name:'CCC',
                                city:'London',
                                orderTotal: 24.999,
                                joined: '2011-08-12'},
                            {
                                name:'BBB',
                                city:'Kenya',
                                orderTotal: 140.4852,
                                joined: '1981-06-04'},
                            {
                                name:'DDD',
                                city:'Tokyo',
                                orderTotal: 77.3654,
                                joined: '2006-10-30'}
                        ]

  $scope.doSort = function(propName) {
    $scope.sortIt = propName;

    //changing the value to opposite if true then false, if false then true
    $scope.reverse = !$scope.reverse; 
  }

HTML:

<table class="table table-striped">
      <thead>
        <tr>
          <th ng-click="doSort(name)" class="btn-arrange">
            Name
          </th>
          <th>
            <span>City</span>
          </th>
          <th>Order Total</th>
          <th>Joined</th>
        </tr>
      </thead>
      <tbody>
        <tr ng-repeat="c in customers | orderBy: sortIt: reverse">
          <td>{{c.name}}</td>
          <td>{{c.city}}</td>
          <td>{{c.orderTotal}}</td>
          <td>{{c.joined}}</td>
        </tr>
      </tbody>
    </table>

2 个答案:

答案 0 :(得分:2)

$scope.reverse = !scope.reverse;替换为$scope.reverse = !$scope.reverse;

您在$之前错过了scope

<强>更新

<th ng-click="doSort(name)" class="btn-arrange">替换为<th ng-click="doSort('name')" class="btn-arrange">

Working Demo

答案 1 :(得分:1)

我正在添加此答案,以使用谓词

对所有单个标题值进行排序

<th><a href="" ng-click="predicate = 'name'; reverse=!reverse">Name</a> </th>
<th><a href="" ng-click="predicate = 'city'; reverse=!reverse">City</a> </th>
<th><a href="" ng-click="predicate = 'orderTotal'; reverse=!reverse">Order Total</a></th>
<th><a href="" ng-click="predicate = 'joined'; reverse=!reverse">Joined</a></th>

<tr ng-repeat="c in customers | orderBy:predicate:reverse">
<td>{{c.name}}</td>
<td>{{c.city}}</td>
<td>{{c.orderTotal}}</td>
<td>{{c.joined}}</td>

相关问题