AngularJS filter : orderBy
Introduction:
AngularJS Filter orderBy is used order an array based on provided predicate expression.
The sign of the filter sets the order, (+ is ascending) while (- is descending)
Syntax:
{{ orderBy_expression | orderBy : expression: reverse}}
<!-- html code -->
<script>
$filter('orderBy')(array, expression, reverse) // javascript filters
</script>
Arguments Detail
Param | Type | Explanation |
---|---|---|
array | array | To array to be ordered. |
expression | function string |
The predicate or logic to be used for comparison |
reverse | boolean | To reverse the array order. |
Example:
AngularJS Filter Number
<!DOCTYPE html>
<html>
<head>
<title>AnngularJS Filters : orderBy </title>
<script src="angular.js"></script>
<style>
.tabled {
float: left;
padding: 10px;
}
</style>
</head>
<body ng-app="orderByDemo">
<script>
angular.module('orderByDemo', [])
.controller('orderByController', ['$scope', function ($scope) {
$scope.countries =
[{ name: 'USA', states: '51', gdp: 19 },
{ name: 'CHINA', states: '28', gdp: 18 },
{ name: 'INDIA', states: '30', gdp: 9 },
{ name: 'GERMANY', states: '16', gdp: 5 },
{ name: 'JAPAN', states: '14', gdp: 4 }];
}]);
//in javascript
$scope.countries = $filter('orderBy')($scope.countries, 'gdp', false);
</script>
<div ng-controller="orderByController">
<table class="tabled">
<tr>
<th>Name</th>
<th>No of States</th>
<th>GDP(descending)</th>
</tr>
<tr ng-repeat="country in countries | orderBy:'-gdp'">
<!-- orderBy Descending (-) -->
<td>{{country.name}}</td>
<td>{{country.states}}</td>
<td>{{country.gdp}}</td>
</tr>
</table>
<table class="tabled">
<tr>
<th>Name</th>
<th>No of States</th>
<th>GDP(ascending)</th>
</tr>
<tr ng-repeat="country in countries | orderBy:'gdp'">
<!-- orderBy Ascending (+) -->
<td>{{country.name}}</td>
<td>{{country.states}}</td>
<td>{{country.gdp}}</td>
</tr>
</table>
</div>
</body>
</html>
Conclusion:
It will be helpfull to apply filter orderBy in angularJS.
0 Comments