Angularjs删除JSon对象

Angularjs delete JSon object

本文关键字:对象 JSon 删除 Angularjs      更新时间:2023-09-26

所以我在这里没有什么困难。我有一个嵌套的json对象,它在ng repeat中,可以使用AngularJS UI sortable(基于JQuery UI sortable)进行排序:

$scope.rootItem = {
        id: '1',
        type: 'course',
        title: 'Adobe Photoshop CC for beginners',
        items: [{
            id: '2',
            type: 'label',
            title:'label',
            items:[{
                id: '3',
                type: 'module',
                title:'Module title',
                items: [{
                    id: '4',
                    type: 'topic',
                    title:'Topic title',
                    items: [{
                        id: '5',
                        type: 'content',
                        title:'Content title'
                    }, {
                        id: '6',
                        type: 'content',
                        title:'Content title'
                    }]
                }]
            },{
                id: '7',
                type: 'resources',
                title:'Resources'
            },{
                id: '8',
                type: 'module',
                title:'Module title',
                items: [{
                    id: '9',
                    type: 'topic',
                    title:'Topic',
                    items: [{
                        id: '10',
                        type: 'question',
                        title:'Question title'
                    }]
                }, {
                    id: '11',
                    type: 'topic',
                    title:'Topic title',
                    items: [{
                        id: '12',
                        type: 'content',
                        title:'Content title'
                    }]
                }]
            }]
        },{
            id: '14',
            type: 'assessmentLabel',
            title: 'Assessment Label',
            items: [{
                id: '15',
                type: 'assessment',
                title: 'Assessment Title',
                items: [{
                    id: '16',
                    type: 'courseAssessment',
                    title: 'Course Question Group',
                    items: []
                }]
            }]
        }]
    };

我应该能够做的是删除这个对象中的任何项目,如果它有任何子项,也需要删除它们。

所以我通常认为传递$index并使用splice来移除它(如果它是一个数组)。

但对于似乎不这样工作的对象,我在网上读到应该使用delete。。。

在我的按钮上,我试图传递对象本身,如:

data-ng-click="removeItem(ngModelItem)"

在我的控制器中做这样的事情:

// Remove Item from the list
    $scope.removeItem = function(item) {
    };

有什么建议吗?

使用ngModelItem

<li ng-repeat="innerItem in ngModelItem.items">
    <a href="#" ng-click="deleteItem(ngModelItem.items, $index)">Delete me</a>

在您的控制器中,

$scope.deleteItem = function(collection, index){
    collection.splice(index,1);
};

演示

要从json对象中删除json元素,请使用delete运算符。但在您的情况下,我假设您想从json数组中删除一个json对象,所以您应该真正使用splice()。

您应该在removeItem()函数中同时接收列表和索引,这样您就可以删除索引元素,angularjs将更新您的视图。