javascript - Remove a object from a JSON object list - Stack Overflow

HTML code:<li ng-repeat="obj in objects">{{obj.name}} <a ng-click="remove($inde

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
 |  Show 2 more ments

1 Answer 1

Reset to default 4

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745187037a4615686.html

相关推荐

  • javascript - Remove a object from a JSON object list - Stack Overflow

    HTML code:<li ng-repeat="obj in objects">{{obj.name}} <a ng-click="remove($inde

    11小时前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信