AngularJS orderBy Filter
Definition and Usage
orderBy
Filters allow us to sort arrays.
By default, strings are sorted alphabetically and numbers are sorted numerically.
Related Pages
AngularJS Tutorial:Angular Filters
Instance
Example 1
Display items in alphabetical order:
<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>
Example 2
Sort the array by "city": <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 Takeout Foods", "city" : "Buenos Aires"}, {"name" : "Bolido Prepared Foods", "city" : "Madrid"}, {"name" : "Around the Horn", "city" : "London"}, {"name" : "B's Beverages", "city" : "London"} }); </script>
Example 3
Sort the array in descending order by "city": <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 Takeout Foods", "city" : "Buenos Aires"}, {"name" : "Bolido Prepared Foods", "city" : "Madrid"}, {"name" : "Around the Horn", "city" : "London"}, {"name" : "B's Beverages", "city" : "London"} }); </script>
Syntax
{{ array | orderBy : expression : reverse }}
Parameters
Parameters | Description |
---|---|
expression |
Expression used to determine the order. The expression can be of the following types: String: If the array is an array of objects, you can sort the array by the value of one of the object properties. See the example above. Function: You can create a function to organize sorting. Array: If you need to determine the sorting order of multiple object properties, use an array. Array items can be strings and functions. |
reverse | Optional. If you want to reverse the order of the array, set it to true. |