Filters can be used with a binding expression or a directive using | orderBy for sorting the data.
{{ <expression> | orderBy : <expression> [: <reverse>] }}
Example
Sorts the employee data by salary in ascending order
<tr ng-repeat="employee in employees | orderBy:'salary':false">
OR
<tr ng-repeat="employee in employees | orderBy:'+salary'">
OR
<tr ng-repeat="employee in employees | orderBy:'salary'">
Default setting for reverse (if +/- or reverse flag is not given) is false.
EXAMPLE
JS
var app = angular.module('module1', []);
app.controller("myController", function ($scope) {
var employees = [
{ name : "Shaan", gender : "Male", salary : 25000 },
{ name : "Renu", gender : "Female", salary : 47000 },
{ name : "Rahul", gender : "Male", salary : 35000 },
{ name : "Anju", gender : "Female", salary : 18000 }
]
$scope.employees = employees;
$scope.sortColumn = "name";
});
HTML
<body ng-app="module1">
<div ng-controller="myController">
Order by :
<select ng-model="sortColumn">
<option value="name">Name ASC</option>
<option value="+gender">Gender ASC</option>
<option value="-salary">Salary DESC</option>
</select>
<table>
<thead>
<tr> <th>Name</th> <th>Gender</th> <th>Salary</th> </tr>
</thead>
<tbody>
<tr ng-repeat="employee in employees |orderBy:sortColumn">
<td> {{ employee.name }} </td>
<td> {{ employee.gender }} </td>
<td> {{ employee.salary }} </td>
</tr>
</tbody>
</table>
</div>
It will display sorted employee data according to selected field and order.
No comments:
Post a Comment
Note: only a member of this blog may post a comment.