5

I have a situation that is pretty similar to this answer to the question here:

AngularJS ng-include with nested hierarchy

I have some data in the format

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

};

And I am display it with a recursive ng-include like this:

  <ul>
   <li>{{data.text}}</li>
   <li ng-repeat="item in data.comments" ng-include="'tree'"></li>
 </ul>

 <script type="text/ng-template" id="tree">
  <ul>
    <li ng-repeat="text in item.text">{{text}}</li>
    <li ng-repeat="item in item.comments" ng-include="'tree'"></li>
  </ul>
</script>

http://plnkr.co/edit/8swLos2V6QRz6ct6GDGb?p=info

However, I would like to somehow keep track of the depth of the recursion as well. So that instead of simply displaying:

-blah
    -blahL11
    -blahL12
    -blahL13
            -blahL111

It could display

-1. blah    
    -2. blahL11
    -2. blahL12
    -2. blahL13
        -3. blahL111

Without me modifying the data structure (as the depth is only really for display?). Can I insert a variable into the ng-include, is there some sort of recursive $index I can use?

1
  • have a look at github.com/dotJEM/angular-tree, it has this built in and otherwise works allot like recursive ng-includes. Commented Oct 27, 2015 at 12:01

1 Answer 1

4

You can do this using ng-init. This will assign a value to the new scope when it's created, which you can do by refering to a value in the old scope and incrementing it.

plnkr demo

<li ng-repeat="item in item.comments" ng-include="'tree'" ng-init="depth = depth + 1"></li>
Sign up to request clarification or add additional context in comments.

1 Comment

That's awesome! I was trying to use onload, didn't think of ng-init. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.