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?

Vladyslav Sharapat
  • 93
  • 1
  • 4
  • 11
  • 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. – Yogesh Jun 28 '16 at 09: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 – Chanthu Jun 28 '16 at 09:56
  • 1
    Please post code containing the `ng-repeat` part, it is currently hard to figure how you manage `$scope/vm` – Icycool Jun 28 '16 at 09:58
  • This code can be correct if only you have `var blog = $scope;` because you call `$scope.remove` by `ng-click="remove()"` – vp_arth Jun 28 '16 at 10:08
  • please share more code from html part of your program – Avantika Saini Jun 28 '16 at 10:11

2 Answers2

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?

Community
  • 1
  • 1
Gauthaman Sahadevan
  • 923
  • 1
  • 11
  • 19
-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>
Avantika Saini
  • 792
  • 4
  • 9