递归ng-repeat重复x次

4

我需要在我的angular模板中遍历一个深度嵌套的javascript对象。问题是我无法控制数据的传递方式,也无法知道数据的嵌套深度。

数据长这样:

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

还有模板

<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>

这个检查两个级别深度,但是怎样才能递归重复直到没有子元素了呢?我在想我需要创建一个自定义指令,按需编译一个新的ng-repeat,只是我不确定该如何去做。

2个回答

3
你可以使用带有指令脚本类型ng-template/textng-include并递归调用它来编写n个子级。(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>

0

请尝试以下方法:

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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接