AngularJS的子列表数量未知

Unknown number of sublists with AngularJS

本文关键字:未知 列表 AngularJS      更新时间:2023-09-26

我正在构建一个工具来帮助用户浏览我们的网站。AngularJS函数从另一个服务接收一个JSON对象,然后打印出一个html5列表。

html应该看起来像

<ul>
<li>Root
  <ul>
      <li>
        Child 2
        <ul>
          <li>Grand Child 1</li>
          <li>Grand Child 2</li>
        </ul>
      </li>
  </ul>
</li>
</ul>

做一个简单的嵌套ng重复(如下所示)会很容易给我一组子元素,但我不确定用Angular设置函数的最佳方式是什么,在Angular中我有未知数量的子元素。

<li ng-repeat="node in nodes">
    <a href="#">{{node.title}}</a>
    <ul>
        <li ng-repeat="child in node.children">
            <a href="#">{{child.title}}</a>
        </li>
    </ul>
</li>

JSON对象示例:

{ 
    title:'University',
    children: [
        { 
            title:'College of Engineering',
            children: [
                { title:'Computer Science' },
                { title:'Electrical Engineering' },
                { title:'Chemical Engineering' },
                { title:'Biological Engineering' },
                { title:'Mechanical Engineering' },
                { title:'Civil Engineering' },
                { title:'Environmental Engineering' }
            ]
        },
        { title:'College of Liberal Arts' },
        { title:'College of Science' },
        { title:'College of Math' }
    ]
}

下面是一个使用递归局部视图显示列表的示例

partial.html

<ul>
    <li ng-repeat="c in data">
      {{c.title}}
      <div ng-switch on="c.children.length > 0">
        <div ng-switch-when="true">
          <div ng-init="data = c.children;" ng-include="'partial.html'"></div>  
        </div>
      </div>
    </li>
</ul>

DEMO

这里有一种作为指令(jsfiddle)编写的替代方法:

angular.module('the-app', []).directive('arbitraryNesting', [
'$compile', 
function($compile){
  var template = ''
<li ng-repeat="datum in data">{{datum.title}}'
  <ul ng-if="datum.children && datum.children.length > 0" arbitrary-nesting="datum.children">'
  </ul>'
</li>';
  var compiledTemplate;
  return {
      restrict: 'A',
      scope: { 'data': '=arbitraryNesting' },
      terminal: true,
      link: function(scope, element) {
          compiledTemplate = compiledTemplate || $compile(template);
          var newScope = scope.$new();
          var linked = compiledTemplate(newScope);
          element.append(linked);
      }
  }
}])