AngularJS ng-include with nested hierarchy

I have a requirement to create a horizontal binary tree structure that does not look like the typical nested tree <ul />that I see using the directive ng-repeat.

How to use ng-include and either pass its nested objects, or somehow get the nested objects that I need?

Here is the code:

<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>

In the template #treeyou can see 2 directives ng-include. I would like $scopefor each nested to ng-includeuse the next level down in the hierarchy on $scope.data, which would be leftChildrenand rightChildren.

In other words, I basically want the same effect ng-repeatwhen calling nested arrays in $scope.

Hope this all makes sense :)

+2
1

, . ng-include . "" . onload, ng-init, ng-model .., ng-repeat, , .

Plunker. , , , . , ng-repeat . . , , , ..

( ):

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>
+7

Source: https://habr.com/ru/post/1605782/


All Articles