Use 2 variables to store the 2 parameters in orderBy filter : Field name and Reverse order flag.
{{ <expression> | orderBy : <expression> [: <reverse>] }}
Set these variables in a function which are called on click on the column headers.
Also, set the CSS class in another function to display correct arrow for ASC or DESC order.
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";
$scope.reverseSort = false;
$scope.sortData = function(column){
$scope.reverseSort = ($scope.sortColumn == column) ?
!$scope.reverseSort : false;
$scope.sortColumn = column;
}
$scope.getSortClass = function(column){
if($scope.sortColumn == column) {
return $scope.reverseSort ? 'arrow-down' : 'arrow-up'
}
}
});
HTML
<body ng-app="module1">
<div ng-controller="myController">
<table>
<thead>
<tr>
<th ng-click="sortData('name')">Name
<div ng-class="getSortClass('name')"> </div>
</th>
<th ng-click="sortData('gender')">Gender
<div ng-class="getSortClass('gender')"> </div>
</th>
<th ng-click="sortData('salary')">Salary
<div ng-class="getSortClass('salary')"> </div>
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="employee in employees
| orderBy:sortColumn:reverseSort">
<td> {{ employee.name }} </td>
<td> {{ employee.gender }} </td>
<td> {{ employee.salary }} </td>
</tr>
</tbody>
</table>
</div>
It will display sorted employee data according to values set in fields sortColumn and reverseSort using 2 functions.
It also sets the CSS class to display up or down arrows.
No comments:
Post a Comment
Note: only a member of this blog may post a comment.