我如何能得到一个反向数组在角? 我试图使用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>

当前回答

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

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

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

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

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

其他回答

从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>

你也可以使用.reverse()。它是一个原生数组函数

<div ngn -repeat=“朋友们的朋友。反向()”>{{朋友}</div>

这是因为您使用的是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修改原始数组。

您可以通过$index参数进行反转

<tr ng-repeat="friend in friends | orderBy:'$index':true">