AngularJS : index not updating after removing array item(s) by index

3.4k views Asked by At

I am trying to remove an item from AngularJS's scope array variable using the index of the item.

(if you're to stop reading here thinking this is a duplicate, please jump to foot note links, I was able to find similar but not same questions which were answered - Or, I could have missed something so if you find EXACTLY same question I'd appreciate if you would please share the SO link for it ! Thx)

here is my example :

http://jsbin.com/seyaje/3/edit?html,output 

The problem I see is, the index does not get updated automatically - every time - hence wrong item gets deleted or if the index is 'out of bounds' the item does not get deleted at all.

What I personally prefer is to pass index in my scenario, and I think it is relatively less work about not having to figure out indexes repetitively. (if the index is correct !)

How could I possibly fix this using AngularJS 1.25 ? Your constructive help is always appreciated !


This might be a similar question to followings :

AngularJS remove item from scope How to remove an Item from scope AngularJS

What I am trying to accomplish, seems little similar to :

https://stackoverflow.com/a/23810035 or http://plnkr.co/edit/51SNVMQjG3dsmpYI5RyY?p=preview

Somewhat similar unanswered question (finds the object and deletes by index): remove clicked item angularjs

1

There are 1 answers

3
Explosion Pills On BEST ANSWER

The myIndex property gets set by the initialization of the repeat and it isn't updated appropriately. Instead you could just work with $index. This will update appropriately when the array changes and delete the correct elements.

<tr ng-repeat="i in items">
    <td>{{$index}}</td>
    <td>{{i.Id}}</td>
    <td>{{i.Name}}</td>
    <td>{{i.Type}}</td>
    <td>
        <button data-ng-click="deleteItemByIndex($index)">&times;</button>
    </td>
</tr>