2

Being new to Angular and Firebase, naturally AngleFire is giving me troubles. I'm using ng-repeat to iterate over a synced array, and I'd like to reverse the order it's displaying. I've tried '| reverse' as well as variations of that, sorting the array on the FireBase side, and copying the array into a local only array then reversing it; among more things than I can remember at this point.

JS adding data to array

ctrl.go = function() {
  console.log(ctrl.localArray);
  ctrl.localArray.$add(
    {
      name: ctrl.name,
      content: ctrl.content,
      time: new Date().getTime(),
    }
  );
  console.log(ctrl.localArray);

HTML w/ ng-repeat

  <span ng-repeat="localArray in ctrl.localArray">
        {{localArray.content}}<br>
        <p class="right">- {{localArray.name}} at {{localArray.time | date : "MMM d, h:mm a"}}</p>
  </span>

What needs to be done to have the ng-repeat display reversed to how it is?

Solution:

<span ng-repeat="localArray in ctrl.localArray.reverse()">
ninjabugs
  • 103
  • 7

1 Answers1

3

You can use Array.prototype.reverse method directly in template:

<span ng-repeat="localArray in ctrl.localArray.reverse()">
    {{localArray.content}}<br>
    <p class="right">- {{localArray.name}} at {{localArray.time | date : "MMM d, h:mm a"}}</p>
</span>

Or you can do it in controller before passing array to HTML.

dfsq
  • 191,768
  • 25
  • 236
  • 258
  • I swear I tried that already, although it's worked beautifully. – ninjabugs Feb 27 '15 at 08:25
  • How would I do so in the controller before passing the array to the HTML? I've tried using passing a different array to the HTML, which is set to ctrl.localArray.reverse() every time something is added to localArray, but then I couldn't get anything to be displayed with ngrepeat. – ninjabugs Feb 27 '15 at 08:30
  • To answer your last comment -- You can use a custom filter. See this answer: http://stackoverflow.com/a/15267754/1526037 – sbolel Feb 28 '15 at 05:36