如何从AngularJS数组中删除项目?

3
为什么我无法从数组中删除项目?

删除项目的html标签:
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"
      }
    ]}];

问题可能出在哪里?


一个可能性是你在 remove 函数中传递的索引是错误的。在那个 splice 语句之前,尝试通过 console.log 查看索引。 - Yogesh
1
也许发布更多的代码会更好。仅仅看这些片段很难确定问题出在哪里。我看到的一个问题是 remove 在作用域上被调用了。但是你的定义是在博客本身的。所以,它不应该是 blog.remove($index) 吗?那么,$index 是什么?我猜是从某种repeat中传来的。 - Chanthu
1
请发布包含 ng-repeat 部分的代码,目前很难弄清楚您如何管理 $scope/vm - Icycool
只有当你有 var blog = $scope; 并通过 ng-click="remove()" 调用 $scope.remove 时,这段代码才是正确的。 - vp_arth
请分享您的程序中HTML部分的更多代码。 - Avantika Saini
2个回答

0

-1
如果您正在使用ng-repeat,那么这可能会有所帮助:
<div ng-repeat="key in posts"> <!-- This will use your blog.posts -->
    <button ng-click="posts.splice($index, 1)"> 

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接