©
本文档使用 PHP中文网手册 发布
通过expression
来排序指定的array
。 字符串按字母顺序排序,数字按大小排序。注意:如果你发现数字没被正确排序,请确认它们保存的是数字而不是字符串。
{{ orderBy_expression | orderBy : expression : reverse}}
$filter('orderBy')(array, expression, reverse)
参数 | 类型 | 详述 |
---|---|---|
array | Array | 用于排序的数组。 |
expression | function(*)stringArray.<(function(*)|string)> |
一个用于通过比较来决定元素顺序的声明。 可为下列之一:
|
reverse
(可选)
|
boolean | 对数组进行反向排序。 |
Array | 源数组排序后的副本。 |
<script>
angular.module('orderByExample', [])
.controller('ExampleController', ['$scope', Function($scope) {
$scope.friends =
[{name:'John', phone:'555-1212', age:10},
{name:'Mary', phone:'555-9876', age:19},
{name:'Mike', phone:'555-4321', age:21},
{name:'Adam', phone:'555-5678', age:35},
{name:'Julie', phone:'555-8765', age:29}];
$scope.predicate = '-age';
}]);
</script>
<div ng-controller="ExampleController">
<pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
<hr/>
[ <a href="" ng-click="predicate=''">unsorted</a> ]
<table class="friend">
<tr>
<th><a href="" ng-click="predicate = 'name'; reverse=false">名称</a>
(<a href="" ng-click="predicate = '-name'; reverse=false">^</a>)</th>
<th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th>
<th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th>
</tr>
<tr ng-repeat="friend in friends | orderBy:predicate:reverse">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<td>{{friend.age}}</td>
</tr>
</table>
</div>
也可以手工调用orderBy过滤器,通过注入$filter
,使用$filter('orderBy')
获取过滤器实例,然后使用所需参数调用过滤器实例。
示例:
<div ng-controller="Ctrl">
<table class="friend">
<tr>
<th><a href="" ng-click="reverse=false;order('name', false)">名称</a>
(<a href="" ng-click="order('-name',false)">^</a>)</th>
<th><a href="" ng-click="reverse=!reverse;order('phone', reverse)">Phone Number</a></th>
<th><a href="" ng-click="reverse=!reverse;order('age',reverse)">Age</a></th>
</tr>
<tr ng-repeat="friend in friends">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<td>{{friend.age}}</td>
</tr>
</table>
</div>
angular.module('orderByExample', [])
.controller('ExampleController', ['$scope', '$filter', Function($scope, $filter) {
var orderBy = $filter('orderBy');
$scope.friends = [
{ name: 'John', phone: '555-1212', age: 10 },
{ name: 'Mary', phone: '555-9876', age: 19 },
{ name: 'Mike', phone: '555-4321', age: 21 },
{ name: 'Adam', phone: '555-5678', age: 35 },
{ name: 'Julie', phone: '555-8765', age: 29 }
];
$scope.order = Function(predicate, reverse) {
$scope.friends = orderBy($scope.friends, predicate, reverse);
};
$scope.order('-age',false);
}]);