我有一个使用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;
您可以在控制器上创建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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句