Recursive ng-repeat x times

I need to iterate over deeply nested javascript object in my angular template. The problem is that I have no control over how the data is passed to me and I don't know how deeply the data is nested.

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 think I need to create a custom directive that compiles a new ng-repeat as needed, I just don't know how.

+3


source to share


2 answers


You can use ng-include

with script type directive 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>

      



+1


source


Try the following:

module.js

  var app = angular.module('app', []);
  app.component("category", {
      controller: function() {
        this.data = {
          category_name: 'cat1',
          children: [{
            category_name: 'cat1-A',
            children: [{
              category_name: 'cat1-A-a',
              children: [{
                category_name: 'cat1-A-a-1',
                children: []
              },
              {
                category_name: 'cat1-A-a-2',
                children: []
              }
            ]
            }]
          }]
        };
      },
      template: '<child current-cat="$ctrl.data"></child>'
    });

  app.component("child", {
    template: '<div>{{$ctrl.currentCat.category_name}}' +
      '<div style="padding-left:20px;" ng-repeat="cat in $ctrl.currentCat.children">' +
      '<child current-cat="cat"></child>' +
      '</div>' +
      '</div>',
    bindings: {
      currentCat: '<'
    }
  });

      



index.html

<html>
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.js"></script>
    <script src="module.js"></script>
  </head>
  <body ng-app="app">
    <div>
      <category></category>
    </div>
  </body>
</html>

      

0


source







All Articles