AngularJS orderBy 过滤器

实例

按字母顺序显示项:

  1. <!DOCTYPE html>
  2. <html>
  3. <script src="https://cdn.bootcdn.net/ajax/libs/angular.js/1.8.2/angular.min.js"></script>
  4. <body>
  5. <div ng-app="myApp" ng-controller="orderCtrl">
  6. <ul>
  7. <li ng-repeat="x in cars | orderBy">{{x}}</li>
  8. </ul>
  9. </div>
  10. <script>
  11. var app = angular.module('myApp', []);
  12. app.controller('orderCtrl', function($scope) {
  13. $scope.cars = ["Dodge", "Fiat", "Audi", "Volvo", "BMW", "Ford"];
  14. });
  15. </script>
  16. <p>数组项按字母顺序显示</p>
  17. </body>
  18. </html>

定义与用法

orderBy 过滤器让我们可以对数组进行排序。

默认情况下,字符串按字母顺序排序,数字按数字排序。


语法

  1. {{ array | orderBy : expression : reverse }}

参数值

描述
expression用于确定顺序的表达式。该表达式可以是:

String: 如果数组是一个对象数组,则可以根据其中一个对象属性的值对数组进行排序。请参见下面的示例。

Function: 您可以创建一个函数来排序。

Array: 如果需要多个对象属性来确定排序顺序,请使用数组。数组项可以是字符串,也可以是函数
reverse可选。如果要反转数组的顺序,请将其设置为 true

更多实例

实例

用 "city" 对数组排序:

  1. <!DOCTYPE html>
  2. <html>
  3. <script src="https://cdn.bootcdn.net/ajax/libs/angular.js/1.8.2/angular.min.js"></script>
  4. <body>
  5. <div ng-app="myApp" ng-controller="orderCtrl">
  6. <ul>
  7. <li ng-repeat="x in customers | orderBy : 'city'">
  8. {{x.name + ", " + x.city}}
  9. </li>
  10. </ul>
  11. </div>
  12. <script>
  13. var app = angular.module('myApp', []);
  14. app.controller('orderCtrl', function($scope) {
  15. $scope.customers = [
  16. {"name" : "Bottom-Dollar Marketse" ,"city" : "Tsawassen"},
  17. {"name" : "Alfreds Futterkiste", "city" : "Berlin"},
  18. {"name" : "Bon app", "city" : "Marseille"},
  19. {"name" : "Cactus Comidas para llevar", "city" : "Buenos Aires"},
  20. {"name" : "Bolido Comidas preparadas", "city" : "Madrid"},
  21. {"name" : "Around the Horn", "city" : "London"},
  22. {"name" : "B's Beverages", "city" : "London"}
  23. ];
  24. });
  25. </script>
  26. <p>用 "city" 对数组项</p>
  27. </body>
  28. </html>
实例

按 "city" 对数组进行降序排序:

  1. <!DOCTYPE html>
  2. <html>
  3. <script src="https://cdn.bootcdn.net/ajax/libs/angular.js/1.8.2/angular.min.js"></script>
  4. <body>
  5. <div ng-app="myApp" ng-controller="orderCtrl">
  6. <ul>
  7. <li ng-repeat="x in customers | orderBy : '-city'">
  8. {{x.name + ", " + x.city}}
  9. </li>
  10. </ul>
  11. </div>
  12. <script>
  13. var app = angular.module('myApp', []);
  14. app.controller('orderCtrl', function($scope) {
  15. $scope.customers = [
  16. {"name" : "Bottom-Dollar Marketse" ,"city" : "Tsawassen"},
  17. {"name" : "Alfreds Futterkiste", "city" : "Berlin"},
  18. {"name" : "Bon app", "city" : "Marseille"},
  19. {"name" : "Cactus Comidas para llevar", "city" : "Buenos Aires"},
  20. {"name" : "Bolido Comidas preparadas", "city" : "Madrid"},
  21. {"name" : "Around the Horn", "city" : "London"},
  22. {"name" : "B's Beverages", "city" : "London"}
  23. ];
  24. });
  25. </script>
  26. <p>使用减号按降序排列(-city)</p>
  27. </body>
  28. </html>

相关页面

AngularJS 教程: Angular 过滤器

分类导航