Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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 :

http://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

share|improve this question
    
remove your myIndex and ng-init at all, use $index –  vp_arth Nov 25 at 17:06

1 Answer 1

up vote 2 down vote accepted

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>
share|improve this answer
    
Please help me understand : how would "data-ng-init="$index" help ? I am trying your suggestion. –  ablaze Nov 25 at 17:00
    
@ablaze actually you don't even need that –  Explosion Pills Nov 25 at 17:01
    
I've to let it be 3 minutes to mark your suggestion as ans. ... as what you've suggested above, seem to work. Feeling that I should have tried this before spending time to write the question, but I appreciate your instant help ! –  ablaze Nov 25 at 17:07

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.