0

So, I have jsfiddle here.

We can add new nodes and delete all the children in parent node. But how can I delete specific child without iterating array? I know that we can use:

Array.prototype.splice()

If we want to remove, for example, this object (screenshot #1), we can get its index and use splice().

enter image description here

But if I want to remove deeply nested object, I don't want iterate array and use splice(), because of perfomance.

enter image description here

In my console I got only:

Object { name: "Node-8-6-2", menu: false, $$hashKey: "object:151" }

And I don't have an access to nodes of parent array. And I need to iterate all array, so that I could remove it.

Anybody knows solution of this issue?

2
  • Is there any index property in object to be deleted Commented Sep 9, 2015 at 14:37
  • No, only $index, but it doesn't work here, because we have a lot of nested arrays. For example, I will have that specific ID. How can I delete element with it? Commented Sep 9, 2015 at 14:40

2 Answers 2

1

Here is your plunker updated. http://jsfiddle.net/marduke182/uXbn6/2828/

The little changes are:

Adding the parent references to the object using parentNodes .

 $scope.add = function(data) {
        var post = data.nodes.length + 1;
        var newName = data.name + '-' + post;
        data.nodes.push({name: newName,nodes: [], parentNodes: data.nodes});
    };

Create method delete node and pass the $index, do the splice to the parent given the index attribute:

   $scope.delete_node = function(data, index) {
        data.parentNodes.splice(index, 1);
    };

Add the new method to the template:

<script type="text/ng-template"  id="tree_item_renderer.html">
    {{data.name}}
    <button ng-click="add(data)">Add node</button>
    <button ng-click="delete(data)" ng-show="data.nodes.length > 0">Delete nodes</button>
    <button ng-click="delete_node(data, $index)" >Delete node {{$index}}</button>
    <ul>
        <li ng-repeat="data in data.nodes" ng-include="'tree_item_renderer.html'"></li>
    </ul>
</script>
Sign up to request clarification or add additional context in comments.

Comments

1

When you are building your nested tree, you can add a parent attribute to your arrays:

var parentNode = [];
var node = [];
node.parent = parentNode;
parentNode.push(node);

Now, if you want to remove node, you can say:

var index = node.parent.indexOf(node);
node.parent.splice(index, 1);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.