I am trying to iterate from the end of an array to the beginning of it.
For example:
repeater-template.js:
export class RepeaterTemplate {
constructor() {
this.friends = [
'Alice',
'Bob',
'Carol',
'Dana'
];
}
}
repeater-template.html:
<template>
<p repeat.for.reverse ="friend of friends">Hello, ${friend}!</p>
</template>
output:
Hello Dana
Hello Carol
Hello Bob
Hello Alice
I don't think the accepted solution will work if the array mutates. I believe the ideal is to create a value-converter that returns the reversed array without mutating the original one. For instance:
JS
export class App {
message = 'Hello World!';
friends = ['a', 'b', 'c'];
attached() {
//MUTATE!
setTimeout(() => { this.friends.push('d') }, 300);
}
}
export class ReverseValueConverter {
toView(array) {
return array.slice().reverse();
}
}
HTML
<p repeat.for="friend of friends | reverse">Hello, ${friend}!</p>
Running example: https://gist.run/?id=20d00a205e651b6b4d7064e2f57d2675
We can't use a computed-property here because @computedFrom
doesn't support collections yet https://github.com/aurelia/binding/issues/249.
Another possible solution is subscribing the array via BindingEngine and updating a reversed copy when it mutates, but that would be too much code to solve a simple problem.
Hope this helps!
As far as I know Aurelia doesn't have any explicit functions for this, but you could make a simple function in the viewmodel:
reverse(arr) {
return arr.slice().reverse();
}
Then in the view:
<template>
<p repeat.for="friend of reverse(friends)">Hello, ${friend}!</p>
</template>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With