admin管理员组文章数量:1415476
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.
本文标签: javascriptRemove a object from a JSON object listStack Overflow
版权声明:本文标题:javascript - Remove a object from a JSON object list - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745187037a2646733.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论