Reputation: 6344
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().
But if I want to remove deeply nested object, I don't want iterate array and use splice(), because of perfomance.
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?
Upvotes: 0
Views: 85
Reputation: 1813
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>
Upvotes: 1
Reputation: 10528
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);
Upvotes: 1