2015-09-09 56 views
0

所以,我有jsfiddle here

我們可以添加新節點並刪除父節點中的所有子節點。但是,我怎樣才能刪除特定的孩子沒有迭代數組?我知道,我們可以使用:

Array.prototype.splice() 

如果我們要刪除,例如,這個對象(截圖#1),我們可以得到它的索引和使用拼接()。

enter image description here

但是,如果我想刪除深度嵌套的對象,我不想迭代數組,並使用拼接(),因爲性能比較的。

enter image description here

在我的控制檯我只得到:

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

而且我不具有對父陣列的節點的訪問。我需要迭代所有數組,以便我可以將其刪除。

有人知道這個問題的解決方案嗎?

+0

是有刪除的對象中有任何索引屬性 – harishr

+0

不,只有$ index,但它在這裏不起作用,因爲我們有很多嵌套數組。例如,我將擁有該特定ID。我如何使用它刪除元素? –

回答

1

這裏是你的搶劫者更新。 http://jsfiddle.net/marduke182/uXbn6/2828/

小的變化是:

添加到使用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}); 
    }; 

創建方法刪除節點,並通過$指數,做拼接,以給定的索引屬性父:

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

添加新的方法到模板:

<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> 
1

當你建立你的嵌套的樹狀結構,你可以在parent屬性添加到您的數組:

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

現在,如果你想刪除node,你可以說:

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