AngularJS orderBy 过滤器
实例
按字母顺序显示项:
<!DOCTYPE html>
<html>
<script src="https://cdn.bootcdn.net/ajax/libs/angular.js/1.8.2/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="orderCtrl">
<ul>
<li ng-repeat="x in cars | orderBy">{{x}}</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('orderCtrl', function($scope) {
$scope.cars = ["Dodge", "Fiat", "Audi", "Volvo", "BMW", "Ford"];
});
</script>
<p>数组项按字母顺序显示</p>
</body>
</html>
定义与用法
orderBy
过滤器让我们可以对数组进行排序。
默认情况下,字符串按字母顺序排序,数字按数字排序。
语法
{{ array | orderBy : expression : reverse }}
参数值
值 | 描述 |
---|---|
expression | 用于确定顺序的表达式。该表达式可以是: String: 如果数组是一个对象数组,则可以根据其中一个对象属性的值对数组进行排序。请参见下面的示例。 Function: 您可以创建一个函数来排序。 Array: 如果需要多个对象属性来确定排序顺序,请使用数组。数组项可以是字符串,也可以是函数 |
reverse | 可选。如果要反转数组的顺序,请将其设置为 true |
更多实例
实例
用 "city" 对数组排序:
<!DOCTYPE html>
<html>
<script src="https://cdn.bootcdn.net/ajax/libs/angular.js/1.8.2/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="orderCtrl">
<ul>
<li ng-repeat="x in customers | orderBy : 'city'">
{{x.name + ", " + x.city}}
</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('orderCtrl', function($scope) {
$scope.customers = [
{"name" : "Bottom-Dollar Marketse" ,"city" : "Tsawassen"},
{"name" : "Alfreds Futterkiste", "city" : "Berlin"},
{"name" : "Bon app", "city" : "Marseille"},
{"name" : "Cactus Comidas para llevar", "city" : "Buenos Aires"},
{"name" : "Bolido Comidas preparadas", "city" : "Madrid"},
{"name" : "Around the Horn", "city" : "London"},
{"name" : "B's Beverages", "city" : "London"}
];
});
</script>
<p>用 "city" 对数组项</p>
</body>
</html>
实例
按 "city" 对数组进行降序排序:
<!DOCTYPE html>
<html>
<script src="https://cdn.bootcdn.net/ajax/libs/angular.js/1.8.2/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="orderCtrl">
<ul>
<li ng-repeat="x in customers | orderBy : '-city'">
{{x.name + ", " + x.city}}
</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('orderCtrl', function($scope) {
$scope.customers = [
{"name" : "Bottom-Dollar Marketse" ,"city" : "Tsawassen"},
{"name" : "Alfreds Futterkiste", "city" : "Berlin"},
{"name" : "Bon app", "city" : "Marseille"},
{"name" : "Cactus Comidas para llevar", "city" : "Buenos Aires"},
{"name" : "Bolido Comidas preparadas", "city" : "Madrid"},
{"name" : "Around the Horn", "city" : "London"},
{"name" : "B's Beverages", "city" : "London"}
];
});
</script>
<p>使用减号按降序排列(-city)</p>
</body>
</html>
相关页面
AngularJS 教程: Angular 过滤器