Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive ng-repeat x times

I need to repeat over a deeply nested javascript object in my angular template. The problem is that I have no control over how the data is handed to me, and no way of knowing how deeply nested the data will be.

The data looks like this

{
    category_name: 'cat1'
    children: [
        {
            category_name: 'cat1a',
            children: [...]            
        }
    ]
}

And the template

<div ng-repeat="cat in categories">
    <div ng-repeat="subcat in cat.children">
        {{subcat.name}}
        <!-- 
            would like to programatically place an ng-repeat here too 
            if subcat.children.length > 0 
        -->
    </div>
    {{cat.name}}
</div>

This checks two levels deep, but how can I recursively repeat until there are no children left? I'm thinking I need to create a custom directive that compiles a new ng-repeat as required, I'm just not sure how to go about it.

like image 698
richbai90 Avatar asked Oct 26 '25 10:10

richbai90


1 Answers

You can use ng-include with a directive script type ng-template/text and call it recursively to write n children. (PLUNKER)

<body ng-controller="MainCtrl as vm">
  <script type="text/ng-template" id="nested.html">
    {{item.category_name}}
    <ul>
      <li ng-repeat="item in item.children" ng-include="'nested.html'"></li>
    </ul>
  </script>

  <ul>
    <li ng-repeat="item in vm.data" ng-include="'nested.html'"></li>
  </ul>
</body>
  • Check angular docs for more info: https://docs.angularjs.org/api/ng/directive/script
like image 152
The.Bear Avatar answered Oct 28 '25 23:10

The.Bear



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!