我有一组JSON数据,我想在嵌套列表中显示:
JSON采用以下格式:
["Item 1", "Item 2", "Item 3", ["Nested Item 1", "Nested Item 2"]]
html应为:
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>
<ul>
<li>Nested Item 1</li>
<li>Nested Item 2</li>
</ul>
</li>
</ul>
我无法控制JSON,可能会超过2级。
当然,我试过这个:
<ul>
<li ng-repeat="item in data">{{item}}</li>
</ul>
但它不起作用,因为对于嵌套项,它只显示json。
如何在AngularJs中实现嵌套列表?
答案 0 :(得分:0)
看一下最后有完整示例的好blog post。简而言之,您需要构建嵌套指令,其中inner指令将对外部指令进行递归调用:
<body>
<div ng-controller="IndexCtrl">
<collection collection='tasks'></collection>
</div>
</body>
angular.module('APP', [])
.directive('collection', function () {
return {
...
template: "<ul><member ng-repeat='member in collection' member='member'></member></ul>"
}
})
.directive('member', function ($compile) {
return {
...
template: "<li>{{member.name}}</li>",
link: function (scope, element, attrs) {
if (angular.isArray(scope.member.children)) {
element.append("<collection collection='member.children'></collection>");
$compile(element.contents())(scope)
}
}
}
答案 1 :(得分:0)
我找到了一个解决方案,感谢zsong和Blackhole。
结果HTML:
<div ng-app="testApp">
<div ng-controller="TestCtrl">
<script type="text/ng-template" id="/nestedList.html">
<ul>
<li ng-repeat="item in data">
<div ng-switch="isString( item )">
<div ng-switch-when="true">{{item}}</div>
<div ng-switch-when="false">
<!-- Recursive template!! -->
<div ng-include="'/nestedList.html'" ng-init="data = item">
</div>
</div>
</div>
</li>
</ul>
</script>
<div ng-include="'/nestedList.html'"></div>
</div>
</div>
我使用了一个包含自身的递归模板。它非常依赖Unknown number of sublists with AngularJS的答案。另外,我必须将以下代码添加到控制器:
$scope.isString = function (item) {
return typeof item === "string";
};