2

我需要创建一个水平二叉树结构,这与<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指令。我希望$scopefor each 嵌套ng-include在 上使用层次结构中的下一个级别$scope.data,这将是leftChildrenand rightChildren

换句话说,我基本上希望ng-repeat$scope.

希望这一切都有意义:)

4

1 回答 1

7

这让我在了解情况之前稍微思考了一下。该问题与 ng-include 和范围有关。如何将不同的范围“发送”到每个包括。我无法让它与 onload、ng-init、ng-model 等一起工作......所以我想到了 ng-repeat 它创建了一个新的子范围,这正是我们在这里寻找的。

我在这里创建了一个Plunker演示。我不得不重新设计你的数据构建方式,所以我希望你能应用这些修改。诀窍是为左右孩子创建一个数组,并使用 ng-repeat 创建一个子范围。现在,您甚至可以拥有超过 2 个分支机构。您还可以添加一个类型属性,以便您知道哪个是左或右等。

结果(图片链接):

结果

JS(返工数据)

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

HTML(根)

<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>
于 2013-04-25T02:31:53.853 回答