Reputation: 976
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?
Upvotes: 5
Views: 2268
Reputation: 4670
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.
<li ng-repeat="item in item.comments" ng-include="'tree'" ng-init="depth = depth + 1"></li>
Upvotes: 4