2017-03-21 12 views
1

私はangularjsを初めて使っています。json配列の動的メニューを表示したいと思います。JSON Arrayの動的メニュー

{ 
 
"Pages": [{ 
 
\t "PageId": 1, 
 
\t "PageTitle": "Home", 
 
\t "PageContent": "Home Page Content", 
 
\t "MenuType": "MainMenu", 
 
\t "ParentMenu": null, 
 
\t "PageStatus": "Active", 
 
\t "PageType": true 
 
}, { 
 
\t "PageId": 2, 
 
\t "PageTitle": "About", 
 
\t "PageContent": "about content", 
 
\t "MenuType": "SubMenu", 
 
\t "ParentMenu": Home, 
 
\t "PageStatus": "Active", 
 
\t "PageType": true 
 
}, { 
 
\t "PageId": 3, 
 
\t "PageTitle": "Contact", 
 
\t "PageContent": "Contact Us Content", 
 
\t "MenuType": "MainMenu", 
 
\t "ParentMenu": null, 
 
\t "PageStatus": "Active", 
 
\t "PageType": true 
 
}] 
 
}

私は、メニューは次のようになりたい:

- Home 
    - About 
- Contact 

答えで私を助けてください..事前ここ

+0

JSON配列の周りのコードは何ですか? htmlとjs?サンプルスニペットがスニペットエディタで実行される可能性はありますか? – tire0011

+0

これまでに何を試しましたか?あなたのテンプレートはどのように見えますか?コントローラ?指定した情報が不十分です – casraf

+0

JSON配列形式を変更する必要があります。サブメニュー配列は、メインメニューの配列内にある必要があります。例えば。 'About'は 'Home'オブジェクトの中にあるべきです –

答えて

1

に感謝を反復処理する関数ですメニューを開き、Webページの要素にアタッチできるネストされた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>

+0

は@ synthet1cの回答に感謝しています。私はこのメニューをこのようにしたいと思っていますか?https://www.w3schools.com/bootstrap/tryit.asp? filename = trybs_navbar_dropdown&stacked = h私を助けてくれますか? –