Reputation: 255
I'm just getting started with AngularJS and I'm trying to sort my table so that when a tableheader is clicked the rows are sorted per that table header.
Here is my plnkr link: http://plnkr.co/edit/mbTq5865KKNzlvpJJy1l
Here is my relevant code: Controller code:
$scope.setRepoSortOrder = function(order) {
if ($scope.repoSortOrder === order) {
if ($scope.repoSortOrder.charAt(0) === '+') {
order = order.replace('+', '-');
} else {
order = order.replace('-', '+');
}
}
$scope.repoSortOrder = order;
};
Table:
<table>
<thead>
<tr>
<th><a href="" ng-click="setRepoSortOrder('-name')">Name</a></th>
<th><a href="" ng-click="setRepoSortOrder('+stargazers_count')">Stars</a></th>
<th><a href="" ng-click="setRepoSortOrder('-language')">Language</a></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="repo in repos | orderBy:repoSortOrder">
<td>{{repo.name}}</td>
<td>{{repo.stargazers_count | number}}</td>
<td>{{repo.language}}</td>
</tr>
</tbody>
</table>
So when the name th is clicked the rows should be sorted by the names - same with stargazers_count and language. If a th is clicked again it should be sorted in the opposite order (if I click name first it's sorted by names in asc order - if I click it again it's sorted in desc order).
Finally: name and language should initially sort in asc order while stargazers_count should sort in desc order initially.
I've done this myself but I don't know if I'm doing it the best way possible. Since I'm not used to the "angular style" I would like to hear how people familiar with AngularJS would handle this. Please check out the plnkr link to see if you could improve it.
Any replies are appreciated!
Upvotes: 0
Views: 676
Reputation: 11547
One thing that can improve is to use a reverse flag of the orderBy filter like this:
$scope.repoSortOrder = "-stargazers_count";
$scope.isReverse = false;
$scope.setRepoSortOrder = function(order) {
$scope.isReverse = ($scope.repoSortOrder === order) ? !$scope.isReverse : false;
$scope.repoSortOrder = order;
};
Example Plunker: http://plnkr.co/edit/CM1BGkQc0AYbrraAPq8r?p=preview
Upvotes: 1