AngularJS的子列表数量未知
Unknown number of sublists with 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重复(如下所示)会很容易给我一组子元素,但我不确定用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);
}
}
}])
相关文章:
- 要求输入在数据列表中
- 从javascript创建一个列表
- 如何使用jQuery选择下拉列表的值
- 将输入字段中的文本提交到我的数据库,同时将其添加到我的列表中
- 将jsp文件下拉列表中的选定项分配给一个java变量(比如String selection)
- Javascript按钮下拉列表
- 如何使用json将对象列表从java转换为javascript
- 区分JSON中的矩阵和列表列表
- jQuery表单添加不适用于下拉列表
- 用每小时的差值填充数组/列表-从下拉列表中给定两个时间值
- 接受不在列表中的值-引导组合框
- 禁用jQuery中的下拉列表
- AngularJS的子列表数量未知
- 用JavaScript生成下拉列表(未知错误)
- 当列表长度未知时按顺序调用 http.get
- 当列表项的数量未知时,如何在加载每个列表项后立即逐个修改列表项
- 拆分textarea单列列表(未知行数)&以150的csv's显示
- 水平居中包含未知数量元素的无序列表
- 如何用未知数量的子列表创建递归列表
- 用jQuery从未知深度的嵌套JSON构建级联下拉列表