angularJS:ng-在有条件使用时通过给出乱序来重复排序

angularJS:ng-repeat orderby giving scrambled order while used conditionally

我们有一个 ng-repeat 如下所示

 <table class="friend">
<tr>
  <th>Name</th>
  <th>Phone Number</th>
  <th>Age</th>
</tr>
<tr ng-repeat="friend in friends | orderBy:(isSortRequired?'-name':'')">
  <td>{{friend.name}}</td>
  <td>{{friend.phone}}</td>
  <td>{{friend.age}}</td>
</tr>

仅当标志isSortRequiredtrue时才需要根据name排序,否则不需要排序。如果没有,这很好用。 of records is less than or equal to 10.if the number of records are greater than 10 and the flag is false the table shows the records in scrambled order.We 希望它显示在与对象中的顺序相同。

为什么会出现这种行为?这里有一个plunker来说明这个问题。

来自 angular orderBy 过滤器的文档

If no property is provided, then the array element itself is used to compare where sorting.

乱序效果是由于 angular 向数组中的每个对象添加 $$hashKey 属性 引起的。 $$hasKey 不能保证与初始数组的顺序相同,因此它们看起来是 'randomized'.

因此,您要么预先订购数组,要么使用仅在需要订购时才应用 orderBy 过滤器的自定义过滤器。

自定义过滤器可能看起来像这样

.filter('filter', ['$filter', function($filter)
{
  var orderBy = $filter('orderBy');
  return function(input, property, use)
  {
    return use ? oderBy(input, property) : input;
  };
}

您可以通过

在您的订单中使用 reverse 选项来解决它

我已经更改了你的代码

Html 变化

 <table class="friend">
    <tr>
      <th> 
      **<a href="" ng-click="predicate = 'name'; reverse=!reverse">Name</a>**</th>// changes here
      <th>Phone Number</th>
      <th>Age</th>
    </tr>
    **<tr ng-repeat="friend in friends | orderBy:predicate:reverse">**// changes here
      <td>{{friend.name}}</td>
      <td>{{friend.phone}}</td>
      <td>{{friend.age}}</td>
    </tr>
  </table>

我在你的控制器中添加了一个范围对象用于名称排序

$scope.predicate = '-name';

脚本更改

<script>
  angular.module('orderByExample', [])
    .controller('ExampleController', ['$scope', function($scope) {
      $scope.isSortRequired = true;
      $scope.friends =
          [{name:'john', phone:'555-1212', age:10},
           {name:'mary', phone:'555-9876', age:19},
           {name:'mike', phone:'555-4321', age:21},
           {name:'julie', phone:'555-8765', age:29},{name:'A', phone:'555-1212', age:10},
           {name:'B', phone:'555-9876', age:19},
           {name:'C', phone:'555-4321', age:21},
           {name:'D', phone:'555-5678', age:35},
           {name:'E', phone:'555-8765', age:29},{name:'F', phone:'555-1212', age:10},
           {name:'G', phone:'555-9876', age:19},
           {name:'H', phone:'555-4321', age:21},
           {name:'I', phone:'555-5678', age:35},
           {name:'J', phone:'555-8765', age:29}];
    }]);

    $scope.predicate = '-name';// ans also some change here
</script>

我已经更新了你的 plunker Demo

The plunker only help to sort the name column only, if you want to sort all columns, then you need to do the same way for your all columns.