sathish salvador
sathish salvador

Reputation: 320

Remove a object from a JSON object list

HTML code:

<li ng-repeat="obj in objects">{{obj.name}} <a ng-click="remove($index)">x</a></li> 

JavaScript code:

$scope.remove = function(index){
    $scope.objects.splice(index, 1);
}

JSON data:

{
    "0": { "name": "name1" },
    "1": { "name": "name2" }
}

When remove() is called, I get TypeError: $scope.objects.splice is not a function, here I know $scope.objects is not an array and so splice() will not work.

Is there any method to remove the selected index??

Thanks in advance...

Upvotes: 0

Views: 7404

Answers (1)

Daniel
Daniel

Reputation: 6481

Since you're using a json object and not an array you can use ng-repeat like this

<li ng-repeat="(key,value) in objects">{{value.name}} <a ng-click="remove(key)">x</a></li> 

So that the remove method can delete current list element by key:

$scope.remove = function(key) {
     delete $scope.objects[key];
}

Here's a plunker.

$index is quite confusing in cases like this as it is dynamic whereas the keys are not.

Upvotes: 4

Related Questions