Let’s assume, I have an array of data in JSON and I’ll the define the data in an employees object in my controller.
$scope.employees = {}
The data consists of employee joining date in the form of string along with name and age (the value for age is numeric). I wish to show and filter the data using the date value. I’ll use the ng-repeat directive along with the orderBy filter.
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script> </head> <body> <div ng-app="myApp" ng-controller="myController"> <!-- FOR '-joinDate' THE PREDICATE IS SET USING '-' (HYPHEN) KEY FOR DESCENDING ORDER. --> <div ng-repeat="emps in empArray | orderBy : '-joinDate'"> <div> {{ emps.joinDate | date : 'dd/MM/yyyy' }} : {{ emps.values.name }} </div> </div> </div> </body>
As you can see in the markup above, I am using the orderBy filter with ng-repeat for the field joinDate. Now, if you do not add the predicate - (hyphen) or if it’s missing, it would sort the list in ascending order. Therefore, I have added the “-” (hyphen) before the field to sort the list in descending order.
ng-repeat="emps in empArray | orderBy : '-joinDate'"
Now, let’s create the data structure for the demo to work. I’ll create the employees object using a JSON structure inside the controller.
<script> angular.module("myApp", []) .controller('myController', ['$scope', function ($scope) { // CREATE AN 'employees' OBJECT, WITH AN ARRAY OF DATA. $scope.employees = { "05/17/2015": { 'name': 'Alpha', 'age': 37 }, "03/25/2016": { 'name': 'Bravo', 'age': 27 }, "09/11/2015": { 'name': 'Charlie', 'age': 29 }, "01/07/2016": { 'name': 'Delta', 'age': 19 }, "03/09/2014": { 'name': 'Echo', 'age': 32 } } $scope.empArray = Object.keys($scope.employees) .map(function (value, index) { return { joinDate: new Date(value), values: $scope.employees[value] } } ); } ]); </script> </html>
Output
The object employees with JSON data has an unordered list of data. That is, I have added the date values randomly along with the employee name and age. I’ll first convert the object to an array so we can return the data to our view and its easy to sort an array than an object.
However, you must focus on one important thing here. Since, the date is in string format in the JSON, we’ll convert the string data to date format and then return the array. This would help sort the list with date in either ascending or descending order.
Similarly, you can now sort using the other two fields also, that is, name and age. Simply replace the orderBy : 'joinDate' with other fields like this.
Sort by “name” in Descending Order
ng-repeat="emps in empArray | orderBy : '-values.name'"
Sort by “age” in Descending Order
ng-repeat="emps in empArray | orderBy : '-values.age'"
Remove the predicate “-” and it would sort and show results in default order, that is, in ascending order.