2013-04-24 90 views
2

我有一個需求來創建一個水平二叉樹結構,它不像我使用ng-repeat指令看到的典型嵌套​​。嵌套層次結構的AngularJS ng-include

如何使用ng-include並傳遞嵌套對象或以某種方式獲取我需要的嵌套對象?

下面的代碼:

<div id="tree-container" ng-controller="CommentController"> 
    <ul class="root-tree" id="current-tree"> 
     <li class="root node"> 
      <div class="feed"> 
       <div class="comment">{{data.comment}}</div> 
      </div> 
     </li> 
     <li class="root-children"> 
      <ul class="tree" ng-include="'tree'"></ul> 
     </li> 
    </ul> 
</div> 

<script> 
    app.controller("CommentController", ["$scope", function ($scope) { 
     $scope.data = { 
      comments: "blah", 
      leftChildren: { 
       comments: ["blah", "blah", "blah"], 
       leftChildren: { comments: ["blah", "blah", "blah"] }, 
       rightChildren: { comments: ["blah", "blah", "blah"] } 
      }, 
      rightChildren: { comments: ["blah", "blah", "blah"] } 
     }; 
    )]); 
</script> 

<script type="text/ng-template" id="tree"> 
    <li class="node"> 
     <div class="feed"> 
      <div class="comment" ng-repeat="comment in data.leftChildren">{{comment.comment}}</div> 
     </div> 
    </li> 
    <li class="node"> 
     <div class="feed"> 
      <div class="comment" ng-repeat="comment in data.rightChildren">{{comment.comment}}</div> 
     </div> 
    </li> 
    <li class="left-children"> 
     <ul class="tree" ng-include="'tree'"></ul> 
    </li> 
    <li class="right-children"> 
     <ul class="tree" ng-include="'tree'"></ul> 
    </li> 
</script> 

可以在#tree模板看到我有2個ng-include指令。我希望每個嵌套的ng-include$scope都能使用$scope.data上的層次結構中的下一個層次,這將是leftChildrenrightChildren

換句話說,我基本上想要ng-repeat在調用$scope中的嵌套數組時具有相同的效果。

希望這一切有意義:)

回答

7

它讓我瞭解情況之前想到了一點。這個問題與ng-include和範圍有關。如何「發送」不同的範圍到每個包括。我無法使用onload,ng-init,ng-model等......所以我想到了ng-repeat,它創建了一個新的子範圍,這正是我們在這裏尋找的。

我在這裏創建了一個Plunker演示。我不得不重新構建數據的方式,所以我希望你可以應用這些修改。訣竅是爲左右兒童創建一個數組,並使用ng-repeat創建一個子範圍。現在,你甚至可以有兩個以上的分支。您還可以添加一個類型屬性,所以你知道哪個是左或右等

結果(link to image):

result

JS(重做數據)

$scope.data = { 
    text: "blah", 
    comments: [ 
    { 
     text: ["blahL11", "blahL12", "blahL13"], 
     comments: [ 
     { 
      text: ["blahL111", "blahL112", "blahL113"] 
     }, 
     { 
      text: ["blahR111", "blahR112", "blahR113"] 
     } 
     ] 
    }, 
    { 
     text: ["blahR11", "blahR12", "blahR13"] 
    } 
    ] 
}; 

HTML(root)

<ul> 
    <li>{{data.text}}</li> 
    <li ng-repeat="item in data.comments" ng-include="'tree.html'"></li> 
</ul> 

模板(兒童)

<div>Child</div> 
<ul> 
    <li ng-repeat="text in item.text">{{text}}</li> 
    <li ng-repeat="item in item.comments" ng-include="'tree.html'"></li> 
</ul>