Removing an object in AngularJS

9.5k views Asked by At

I have a $rootScope object in AngularJS like this:

$rootScope.stuff = {
    someId: {
        name: "Patrick",
        age: 105
    },
    anotherId: {
        name: "Joseph",
        age: 94
    }
};

I have a function defined that adds objects to $rootScope.stuff, and it works fine:

$rootScope.addSomeStuff = function(id, data) {
    $rootScope.stuff[id] = data;
};

However, I also have a function that tries to delete (based on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete), and it is not working:

$rootScope.deleteStuff = function(id) {
    delete $rootScope.stuff[id];
};

When I check $rootScope.stuff[id] I am getting the correct object that I want to delete. I have also tried splice, but that throws an error like I thought it would. Any suggestions? Thanks.

1

There are 1 answers

3
jordajm On BEST ANSWER

Change the object to an array of objects, then pass in the index of the object you want to delete:

$rootScope.stuff = [
    someId: {
        name: "Patrick",
        age: 105
    },
    anotherId: {
        name: "Joseph",
        age: 94
    }
];



$rootScope.deleteStuff = function(index) {
    delete $rootScope.stuff[index];
};

HTML (assuming this is rendered via ng-repeat):

<button ng-click="deleteStuff($index)"></button>

EDIT

If you need to keep the data as an object, it will be a difficult data structure to work with because the ID of each object is actually not an ID but an object with a name and an age. So, I actually don't know if it'll be possible to delete the entire object. You could delete the name and the age but without a unique identifier for the whole object I don't know how you'd delete the object itself.