3

Why I can't remove item from array posts?

html tag for delete item

html tag
<span ng-click="remove($index)"> delete</span>

//AngularJS method where I try to delete item
blog.remove = function(index) {
blog.posts.splice(index, 1);
};

//Angular array posts
blog.posts = [{
    "title": "Blog Post One",
    "comments": [
      {
        "body":"Lorem ipsum dolor sit amet, consectetur adipisicing elit. ",
        "author": "trollguy87"
      }
    ]}];

Where can be problem?

5
  • one possibility is that index you are passing in your remove function is wrong. Try to see index by console.log, before that splice statement. Commented Jun 28, 2016 at 9:56
  • 1
    Maybe post a bit more code. Hard to tell exactly what's wrong by just looking at these fragment. On problem I see is remove is getting called on scope. But you're definition is on the blog itself. So, shouldn't it be blog.remove($index)? And, what is the $index? Coming from some sort of repeat I assume Commented Jun 28, 2016 at 9:56
  • 1
    Please post code containing the ng-repeat part, it is currently hard to figure how you manage $scope/vm Commented Jun 28, 2016 at 9:58
  • This code can be correct if only you have var blog = $scope; because you call $scope.remove by ng-click="remove()" Commented Jun 28, 2016 at 10:08
  • please share more code from html part of your program Commented Jun 28, 2016 at 10:11

2 Answers 2

0

Try passing the item to the function and getting the index from the item.

As mentioned in the below thread.

How do I delete an item or object from an array using ng-click?

Sign up to request clarification or add additional context in comments.

Comments

-1

If you are using ng-repeat then this can help:

<div ng-repeat="key in posts"> <!-- This will use your blog.posts -->
    <button ng-click="posts.splice($index, 1)"> 

        {{key.title}}
    </button>
</div>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.