AngularJS从范围中删除项目

时间:2014-07-08 08:04:42

标签: angularjs angularjs-ng-repeat

我的模板:

<div ng-repeat="comment in article.comments">
    {{ comment.date }} by {{ comment.author }} <button type="button" ng-click="removeComment($index)">remove</button>
</div>

我的JSON评论:

"comments": [
    {
        "author": "Syl A",
        "date": "2014-07-02",
        "content": "lol"
    },
    {
        "author": "Syl B",
        "date": "2014-07-02",
        "content": "lol"
    },
    {
        "author": "Syl C",
        "date": "2014-07-02",
        "content": "lol"
    }
]

我的控制器:

$scope.removeComment = function (key) {
    // This is what I want to remove
    // Object {author: "Syl A", date: "2014-07-02", content: "lol", $$hashKey: "004"}
    console.log($scope.article.comments[key]);
};

以下代码段不正常,它什么都不做;

$scope.article.comments.splice[key, 1];

以下代码段不正常,该对象已被删除,但在视图中“删除”时,整行不会删除,我无法删除多个项目Error: [ngRepeat:dupes]

$scope.article.comments[key] = undefined;
delete $scope.article.comments[key];

以下代码段不正常,该对象已被删除,但在视图中“删除”后,整个行未被删除:

$scope.article.comments[key] = {};

所以我没有在SO上找到解决方案来制作“一体化”删除,DOM和“数据”。为什么我的splice在这里不起作用?

1 个答案:

答案 0 :(得分:3)

你使用拼接错误是问题。

将拼接更新为使用()而不是[]

$scope.article.comments.splice(key, 1);