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 ), 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.
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/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.
- Could you show me what you did for your splice function? – John Cooling Commented Jun 25, 2015 at 21:17
-
Sure.
$rootScope.stuff.splice($rootScope.stuff[id], 1);
And I got the error "TypeError: $rootScope.stuff.splice is not a function." – psnoonan Commented Jun 25, 2015 at 21:21 - Why don't you think it works? Is there an error? – tymeJV Commented Jun 25, 2015 at 21:22
- Just to confirm - you named the arg that you're passing into the delete method "id" but you're actually passing in the index of the object you want to delect, correct? $rootScope.deleteStuff = function(index) – jordajm Commented Jun 25, 2015 at 21:24
- Splice only works on arrays, correct? $rootScope.stuff is just an object. – psnoonan Commented Jun 25, 2015 at 21:24
1 Answer
Reset to default 5Change 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.