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...
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...
Share Improve this question edited Apr 19, 2015 at 21:44 Misa Lazovic 2,82310 gold badges33 silver badges39 bronze badges asked Apr 19, 2015 at 21:07 sathish salvadorsathish salvador 3205 silver badges16 bronze badges 7-
4
delete $scope.objects[index]
– adeneo Commented Apr 19, 2015 at 21:08 - Need more code for $scope creation – MaxZoom Commented Apr 19, 2015 at 21:16
- The solution by @adeneo worked, but while removing there seems to be another issue, jsfiddle/salvadorcs/9d8ztbpL – sathish salvador Commented Apr 19, 2015 at 21:32
- when i remove name2 and then name1 it works fine, but the other way the name2 is not removed – sathish salvador Commented Apr 19, 2015 at 21:33
- the indexes of $scope.objects remains same after calling remove() – sathish salvador Commented Apr 19, 2015 at 21:39
1 Answer
Reset to default 4Since 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.