3

I stumpled upon this post about how to reverse the display of an array, which is working fine when I try to do it. angular ng-repeat in reverse

However...then itmes I'm listing are editable and when I'm reversing the array the $index is not being reversed so when I edit the 1 item listed the edit happens in another item that holds the correct index.

So how do I make sure that my $index is reversed as well?

So the code looks like this

<form action="" method="post" autocomplete="off" ng-controller="itemCtrl">
 <input type="text" name="createitem" ng-model="item" />
 <button ng-click="addItem(item)">Add item</button>
 
    <ul>
       <li ng-repeat="item in items | reverse">
            <h2>{{item.title}}</h2>
        </li>
    </ul>
</form>

var itemApp = angular.module('itemApp', []);

itemApp.filter('reverse', function() {
 return function(items) {
  return items.slice().reverse();
 };
});

itemApp.controller('itemCtrl', function ($scope) {

            $scope.items = [];

            $scope.addItem = function(item){
                $scope.items.push({
                    title: item
                });

            };
Community
  • 1
  • 1
  • Don't use the index at all, but pass the array element itself. Or reverse the array in the scope, then iterate on it, instead of iterating on a reversed copy of the array. – JB Nizet Sep 28 '14 at 16:40
  • Yeah, that's what I've been trying to do. Could you provide some sample code of the concept? Obviously I have not succeeded so far :-/. –  Sep 28 '14 at 16:47
  • Don't use the filter, and use this to initialize the array in the scope: `$scope.items = items.slice().reverse();`. – JB Nizet Sep 28 '14 at 16:48
  • That's what I've tried to do. But when I do that then the $index is messed up when I edit the items in the list. –  Sep 28 '14 at 16:53
  • Yeah. Must be an issue with your code. But you didn't share any line of it. So how could we help? – JB Nizet Sep 28 '14 at 16:54
  • I know I know...it's coming up... :) –  Sep 28 '14 at 17:04
  • So I just added the code now. Cheers. –  Sep 28 '14 at 17:11
  • That's the original code. Where is the code that does what I advised you to do? If your array is empty at the beginning, and you want newly added items to be at the head of the list, why do you add it at the tail? See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift – JB Nizet Sep 28 '14 at 17:13

1 Answers1

12

Here's what I'm using. You just need to subtract the array length by the current $index:

{{myArray.length - $index}}
ivan_pozdeev
  • 33,874
  • 19
  • 107
  • 152
RenanSS
  • 131
  • 1
  • 8