我需要创建一个水平二叉树结构,它不像我使用<ul />
指令看到的典型嵌套ng-repeat
。
如何使用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
指令。我希望每个嵌套$scope
的{{1}}使用ng-include
层次结构中的下一个级别,即$scope.data
和leftChildren
。
换句话说,我基本上希望在rightChildren
中调用嵌套数组时具有相同的效果ng-repeat
。
希望这一切都有道理:)
答案 0 :(得分:7)
在了解情况之前让我思考了一下。问题与ng-include和范围有关。如何“发送”不同的范围到每个包括。我无法使用onload,ng-init,ng-model等...所以我想到了ng-repeat,它创建了一个新的子范围,这是我们在这里寻找的。 p>
我在这里创建了一个Plunker演示。我不得不重做你的数据构建方式,所以我希望你可以应用这些修改。诀窍是为左右儿童创建一个数组,并使用ng-repeat创建一个子范围。现在,您甚至可以拥有2个以上的分支机构。您还可以添加一个类型属性,以便知道哪个是左或右等。
结果(link to image):
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>