2

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
  • remove your myIndex and ng-init at all, use $index Commented Nov 25, 2014 at 17:06

1 Answer 1

5

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>
Sign up to request clarification or add additional context in comments.

3 Comments

Please help me understand : how would "data-ng-init="$index" help ? I am trying your suggestion.
@ablaze actually you don't even need that
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 !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.