递归ng-重复x次

时间:2017-08-01 23:07:17

标签: javascript angularjs angularjs-ng-repeat

我需要在我的角度模板中重复一个深层嵌套的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 个答案:

答案 0 :(得分:2)

您可以将ng-include与指令脚本类型ng-template/text一起使用,并递归调用它来编写 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>

答案 1 :(得分: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>