2013-04-24 92 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>