我是angularjs的新手,我想从json数组中显示动态菜单。
{
"Pages": [{
"PageId": 1,
"PageTitle": "Home",
"PageContent": "Home Page Content",
"MenuType": "MainMenu",
"ParentMenu": null,
"PageStatus": "Active",
"PageType": true
}, {
"PageId": 2,
"PageTitle": "About",
"PageContent": "about content",
"MenuType": "SubMenu",
"ParentMenu": Home,
"PageStatus": "Active",
"PageType": true
}, {
"PageId": 3,
"PageTitle": "Contact",
"PageContent": "Contact Us Content",
"MenuType": "MainMenu",
"ParentMenu": null,
"PageStatus": "Active",
"PageType": true
}]
}

我希望菜单是这样的:
- Home
- About
- Contact
请帮我解答..提前致谢
答案 0 :(得分:1)
这是一个函数,它将遍历您的菜单并将其转换为嵌套的html列表,您可以将其附加到网页中的元素。
const menu = {
"Pages": [
{ "PageId": 1, "PageTitle": "Home", "ParentMenu": null },
{ "PageId": 2, "PageTitle": "About", "ParentMenu": "Home" },
{ "PageId": 3, "PageTitle": "Contact", "ParentMenu": null },
{ "PageId": 4, "PageTitle": "Our Story", "ParentMenu": "About" },
{ "PageId": 5, "PageTitle": "Our Future", "ParentMenu": "About" },
]
}
// abstracted way to create an element
const createElement = (type, className, text) => {
const el = document.createElement(type)
el.className = className
if (text) {
el.appendChild(document.createTextNode(text))
}
return el
}
// print the menu as a tree
const createMenu = (menu, parentName = null, level = 0) =>
menu.reduce((ul, item) => {
if (item.ParentMenu === parentName) {
const li = createElement(`li`, `menu__item`, item.PageTitle)
ul.appendChild(li)
// recursively call itself changing the parentName to the current PageTitle
const children = createMenu(menu, item.PageTitle, level+1)
if (children.childNodes.length) {
li.appendChild(children)
}
}
return ul
}, createElement(`ul`, `menu__list level--${level}`))
const app = document.querySelector(`#app`)
app.appendChild(
createMenu(menu.Pages, null)
)
console.log(app.innerHTML)
<div id="app"></div>