Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reversing $index when listing items in reversed order

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
                });

            };

1 Answers

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

{{myArray.length - $index}}
like image 142
RenanSS Avatar answered Dec 04 '25 12:12

RenanSS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!