我有一个使用ul
和li
的菜单。我想通过Angular和JSON对象显示它。
我试图通过ng-repeat
来做,但我的问题是如果我的对象有20层嵌套对象,或者另一方面它有n层嵌套子项如何显示它?
html中的代码
<ul>
<li ng-repeat="item in model">
{{item.text}}
</li>
</ul>
和我的json对象是:
var model = [
{ text: "one", link: "#" },
{ text: "tow", link: "#" },
{
text: "three",
link: "#",
children: [
{ text: "four", link: "#" },
{ text: "five", link: "#", children: [{text:"nine", link:"#"}] },
{ text: "six", link: "#" }
]
}];
$scope.model = model;
答案 0 :(得分:1)
您可以在控制器上创建html,然后使用ng-bind-html将其绑定到视图
我建议使用递归方法:
'use strict';
angular.module('yourApp')
.controller('FooCtrl', function($scope) {
var myModel = [
{ text: "one", link: "#" },
{ text: "tow", link: "#" },
{
text: "three",
link: "#",
children: [
{ text: "four", link: "#" },
{ text: "five", link: "#", children: [{ text: "nine", link: "#" }] },
{ text: "six", link: "#" }
]
}
];
var createHtml = function(model) {
var html = '';
for(var i = 0 ; i < model.length ; i++) {
var li = model[i];
html += '<li>';
html += li.text;
if(li.children) {
html += '<ul>';
html += createHtml(li.children);
html += '</ul>';
};
html += '</li>';
}
return html;
}
$scope.myHtml = '<ul>'+createHtml(myModel)+'</ul>';
});
您可以使用
在视图中调用它<div ng-bind-html="myHtml">
</div>
答案 1 :(得分:0)
处理此问题的好方法应遵循composite pattern:
的原则<composite-list items="model"> </composite-list>
复合元素定义如下:
const compositeList = {
scope: {
items: "="
},
restrict: 'E',
template: `
<ul>
<li ng-repeat="item in vm.items">
<a ng-href="{{item.link}}">{{item.text}}</a>
<composite-list ng-if="item.children.length" items="item.children">
</composite-list>
</li>
</ul>
`
}
编辑:不是严格的实施,但它完成了他的工作