AngularJS的子列表数量不明

时间:2013-12-16 18:27:42

标签: javascript angularjs

我正在努力构建一个工具来帮助用户浏览我们的网站。 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-repeat(如下所示)很容易给我一组孩子,但是我不确定用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' }
    ]
}

2 个答案:

答案 0 :(得分:2)

以下是使用递归局部视图显示列表

的一个示例

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

答案 1 :(得分:0)

这是一种作为指令(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);
      }
  }
}])