如何在angularjs中按降序排列对象数组?

Sar*_*rya 8 angularjs angularjs-orderby angular-filters

我有一个非常简单的对象数组,我想$filter('orderBy')在javascript中使用它进行排序.不知怎的,它似乎不起作用.的jsfiddle

这是代码

var app = angular.module('myApp', []);

app.controller('myController', function($scope, $filter){
    var person = [{
  name : "Saras"
  },
  {
  name : "Arya"
  }];
  $filter('orderBy')(person, 'name');
  console.log(person);
});
Run Code Online (Sandbox Code Playgroud)

我不明白为什么我不能让这个工作?感谢帮助.解决方案应该是JS而不是HTML.

Pan*_*kar 8

您应该将第二个参数作为属性名称传递name,然后将过滤后的结果分配给所需的范围变量.因此,在UI ng-repeat输出上不需要进行任何过滤.

$scope.person = $filter('orderBy')(person, 'name');

<div  ng-repeat="p in person">
   {{p.name}}
</div>
Run Code Online (Sandbox Code Playgroud)

叉子小提琴在这里


如果你想在视图上看到它,你应该将该属性保留在一个范围变量上,或者你可以在显示记录时在客户端进行这种简单的过滤.

<div  ng-repeat="p in person | orderBy: 'name'">
   {{p.name}}
</div>
Run Code Online (Sandbox Code Playgroud)

在这里演示

  • 如果你想按降序排序,那么在第三个参数中设置为true,如下所示:$ scope.person = $ filter('orderBy')(person,'name',true); (3认同)

Ale*_*kić 8

在orderBy参数上添加+或 - 前缀将按+(升序)或 - (desc)排序;

例:

<li ng-repeat="x in customers | orderBy : '-city'">
    {{x.name + ", " + x.city}}
</li>
Run Code Online (Sandbox Code Playgroud)

更多内容:http://www.w3schools.com/angular/ng_filter_orderby.asp

或者,如果您想要console.log,那么只需在引用中添加name作为参数:

$filter('orderBy')(person, 'name');
Run Code Online (Sandbox Code Playgroud)