Angular ng-repeat in reverse
Easily reverse the ng-repeat
list in AngularJS by using the orderBy
filter in your HTML:
Easy and effective, this line of code uses Angular's orderBy
filter to sort by the descending $index
, thus reversing the order in which items are shown. No need to modify the controller or any data.
Building a custom filter
Creating the reverse filter
A powerful tool to have in your Angular utility belt is a custom filter. This can be used for not only arrays but adapted for other data types like strings. Below is the basic structure to start creating your own:
Prioritizing type safety
By checking first whether your input is an array, you safeguard against potentially fatal errors and enhance the robustness of your filter:
Ensuring original data integrity
Working with the slice()
method is important because it ensures the original array remains untouched. This way, you keep the integrity of your data intact while having fun rearranging them!
Utilizing and customizing orderBy
Examining the documentation
Reading the AngularJS documentation would make you realise that there are features you may not be aware of, like reversing arrays without extra methods. Though a bit more reading wouldn't hurt, would it?
Uncovering orderBy secrets
Use an object with the reverse:true
attribute to reverse the array without affecting the sort order:
Here, setting reverse
to true
gives you a reversed array sans sorting.
Beyond the array element
If you don't want to sort based on specific fields, use the orderBy
filter with the array element itself as a comparator:
See how versatile orderBy
can be!
Practical use-cases and considerations
Reversing in the controller
Sometimes, you just have to do things the old-fashioned way—like reversing arrays right in the controller. Adding this saves you from editing the view later:
Performance matters
Reversing large arrays or doing so too frequently can lead to performance issues. Remember, efficiency matters as much as execution. Always consider which methods would suit best based on your application's functionalities and usage patterns.
Thinking flexible: Extending to strings
For additional flexibility, consider extending the custom reverse filter to handle different data types like strings. This way, the reverse filter becomes a more useful tool that caters to a wider range of scenarios.
Was this article helpful?