I have recently started learning AngularJS and am currently working on sorting my table by clicking on the table headers. When a header is clicked, I want the rows to be sorted based on that specific header.
If you'd like to see my code in action, here is the plnkr link: http://plnkr.co/edit/mbTq5865KKNzlvpJJy1l
Below is the relevant code snippet:
$scope.setRepoSortOrder = function(order) {
if ($scope.repoSortOrder === order) {
if ($scope.repoSortOrder.charAt(0) === '+') {
order = order.replace('+', '-');
} else {
order = order.replace('-', '+');
}
}
$scope.repoSortOrder = order;
};
This is how my table structure looks:
<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>
By clicking on the table headers for 'Name', 'Stars', or 'Language', you can sort the rows accordingly. Additionally, clicking on a header multiple times will change the sorting from ascending to descending order.
Initially, 'Name' and 'Language' columns are sorted in ascending order, while 'Stars' column is sorted in descending order.
I've implemented this functionality myself, but I'm open to feedback and suggestions on improving it, especially from those experienced with AngularJS. Please take a look at the plnkr link and let me know your thoughts.
Thank you for any input!