AngularJS: table sorting
by pkozlowski_opensource
HTML
<table ng:controller="SortableTableCtrl">
<thead>
<tr>
<th ng:repeat="th in head" ng:class="selectedCls(th.column)" ng:click="changeSorting(th.column)">{{th.head}}</th>
</tr>
</thead>
<tbody>
<tr ng:repeat="row in body | orderBy:sort.column:sort.descending">
<td>{{row.name}}</td>
<td>{{row.surname}}</td>
<td>{{row.city}}</td>
</tr>
</tbody>
</table>
CSS
td { padding: 0.2em 1em; }
th { text-align: center; }
thead {
border-bottom: 2px solid black;
cursor: pointer;
}
/* http://www.greywyvern.com/code/php/binary2base64 */
.sort-true {
background:no-repeat right center...
JavaScript
function SortableTableCtrl($scope) {
// data
$scope.head = [
{head: "Name", column: "name"},
{head: "Surname", column: "surname"},
{head: "City", column: "city"}];
$scope.body = [{
"name": "Hans",
"surname": "Mueller",
"city": "Leipzig"
}, {
"name": "Dieter",
"surname": "Zumpe",
"city": "Berlin"
}, {
"name": "Bernd",
"surname": "Danau",
"city": "Muenchen"
}];
$scope.sort = {
column: 'name',
descending: false
};
$scope.selectedCls = function(column) {
return column == $scope.sort.column && 'sort-' + $scope.sort.descending;
};
$scope.changeSorting = function(column) {
var sort = $scope.sort;
if (sort.column == column) {
sort.descending = !sort.descending;
} else {
sort.column = column;
sort.descending = false;
}
};
}