Skip to content Skip to sidebar Skip to footer

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 d

Solution 1:

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

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

Solution 2:

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><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.js"></script><scriptsrc="module.js"></script></head><bodyng-app="app"><div><category></category></div></body></html>

Post a Comment for "Recursive Ng-repeat X Times"