AngularJS ng-包含嵌套层次结构

Rya*_*yan 2 javascript angularjs

我需要创建一个水平二叉树结构,它不像<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>
Run Code Online (Sandbox Code Playgroud)

你可以在#tree模板中看到我有2 ng-include条指令.我想$scope为每个嵌套ng-include使用层次结构中的下一级别$scope.data,这将是leftChildrenrightChildren.

换句话说,我基本上希望ng-repeat在调用嵌套数组时具有相同的效果$scope.

希望这一切都有道理:)

jpm*_*rin 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"] 
    }
  ]
};
Run Code Online (Sandbox Code Playgroud)

HTML(根)

<ul>
  <li>{{data.text}}</li>
  <li ng-repeat="item in data.comments" ng-include="'tree.html'"></li>
</ul>
Run Code Online (Sandbox Code Playgroud)

模板(儿童)

<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>
Run Code Online (Sandbox Code Playgroud)