2016-11-21 55 views
0

我有一段AngularJs代碼,它以分層方式添加一組元素/模板。它還會刪除各個按鈕單擊的組元素。從層次結構中刪除動態添加的元素/模板(在AngularJs中)

我的問題是我無法刪除/刪除節點,如果它沒有任何孩子。

在刪除功能中,我試圖清空節點,但節點沒有被刪除。

的script.js:

var myapp = angular.module('myApp', []) 
     .controller('nestedController', function($scope){    
      $scope.delete = function(data) { 

       if(data.nodes.length == 0) 
       { 
        data = {}; 
       } 
       // Removes all the children nodes. 
       data.nodes = []; 
      };  
... 
}); 

HTML:

<html ng-app="myApp" ng-controller="nestedController"> 

    <head> 

     <script type="text/ng-template" id="my-tmpl"> 
    {{data.name}} 
    ... 
    <button class="btn" ng-click="delete(data)" >Delete nodes</button> 

    <ul> 
    <li ng-repeat="data in data.nodes" ng-include="'my-tmpl'"></li> 
    </ul> 
</script> 
    </head> 

    <body> 
<ul > 
    <li ng-repeat="data in tree" ng-include="'my-tmpl'"></li> 
</ul> 
</body> 
</html> 

全功能代碼是在Plunker

回答

1

與您的代碼,你不能刪除一個節點,因爲刪除功能你實現的只刪除一個節點的子元素,而不是父節點本身。如果您只想刪除單個子節點,則必須構建另一個函數,該函數接受節點本身的輸入並將其從tree數據結構中移除。如果你實現這樣一個功能,也應該考慮刪除這些子節點。