我如何能得到一个反向数组在角? 我试图使用orderBy过滤器,但它需要一个谓词(例如。'name')排序:

<tr ng-repeat="friend in friends | orderBy:'name':true">
      <td>{{friend.name}}</td>
      <td>{{friend.phone}}</td>
      <td>{{friend.age}}</td>
<tr>

是否有一种方法可以反转原始数组,而不需要排序。 像这样:

<tr ng-repeat="friend in friends | orderBy:'':true">
      <td>{{friend.name}}</td>
      <td>{{friend.phone}}</td>
      <td>{{friend.age}}</td>
<tr>

当前回答

这是因为您使用的是JSON对象。当你面对这样的问题时,把JSON对象改为JSON数组对象。

例如,

{"India":"IN","America":"US","United Kingdon":"UK"} json object
[{"country":"India","countryId":"IN"},{"country":"America","countryId":"US"},{"country":"United Kingdon","countryId":"UK"}] 

其他回答

你可以在你的作用域上调用一个方法来反转它,像这样:

<!doctype html>
<html ng-app="myApp">
<head>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="http://code.angularjs.org/1.0.5/angular.min.js"></script>
    <script>
    angular.module('myApp', []).controller('Ctrl', function($scope) {
        $scope.items = [1, 2, 3, 4];
        $scope.reverse = function(array) {
            var copy = [].concat(array);
            return copy.reverse();
        }
    });
    </script>
</head>
<body ng-controller="Ctrl">
    <ul>
        <li ng-repeat="item in items">{{item}}</li>
    </ul>
    <ul>
        <li ng-repeat="item in reverse(items)">{{item}}</li>
    </ul>
</body>
</html>

注意,$scope。reverse创建数组的副本,因为array. prototype.reverse修改原始数组。

如果你使用的是angularjs 1.4.4及以上版本,一个简单的排序方法是使用"$index"。

 <ul>
  <li ng-repeat="friend in friends|orderBy:$index:true">{{friend.name}}</li>
</ul>

视图演示

有用的提示:

你可以用普通Js来反转你的数组:

注意:反向是破坏性的,所以它会改变你的数组,而不仅仅是变量。

从Angular 1.4.5开始,orderBy过滤器执行稳定的排序。(参见GitHub pull request https://github.com/angular/angular.js/pull/12408)

因此,使用常量谓词和反向设置为true就足够了:

<div ng-repeat="friend in friends | orderBy:0:true">{{friend.name}}</div>

很抱歉在一年后才提出这个问题,但有一个新的、更简单的解决方案,适用于Angular v1.3.0-rc。5及以上。

在文档中提到: “如果没有提供属性,(例如。'+'),然后数组元素本身用于比较排序"。所以,解决方案是:

ng-repeat="friend in friends | orderBy:'-'"或

ng-repeat="朋友中的朋友| orderBy:'+':true"

这种解决方案似乎更好,因为它不修改数组,也不需要额外的计算资源(至少在我们的代码中)。我已经阅读了所有现有的答案,但仍然更喜欢这个答案。