简体   繁体   中英

Accessing data inside nested objects and arrays

I'm making a fairly complex menu system where it should change depending on the authority that has logged in. Now my question is, have I nested it too much? How do I access for example a title in the items, in the admin within the menus? I'm gonna generate the menus using angularJS's ng-repeat so I need to be able to access it via "item in menus.admin.items.title" for example. I figured I should ask now before I add more in case this isn't a viable option.

This is my menu structure inside the angular controller:

$scope.menus = [{
    admin: [{
        title: 'Administration',
        items: [{
                title: 'Hantera utbildningar',
                URL: 'mngprograms'
            },
            {
                title: 'Hantera kurser',
                URL: 'mngcourses'
            },
            {
                title: 'Hantera lärare',
                URL: 'mngteachers'
            },
            {
                title: 'Hantera studenter',
                URL: 'mngstudents'
            }],
        URL: 'administration',
        id: 'administration'
    }]
}]

Here's my failed attempt at accessing it:

EDIT :

To get a clearer view of the whole thing go here: http://jsfiddle.net/52evmfg9/

<ul id="main-menu">
    <li data-ng-repeat="menu in menus" id="{{menu.id}}"><a href="{{menu.URL}}.php">{{menu.title}}</a>
        <ul data-ng-if="menu.admin">
            <li data-ng-repeat="subitem in menu[3].admin.items"><a href="{{subitem.URL}}.php">{{subitem.title}}</a></li>
        </ul>
    </li>
</ul>

How do I write this?

To answer the question in the comments:

<div data-ng-repeat="(k,v) in menus"> 
       <div data-ng-repeat="(k,w) in v"> 
            <div data-ng-repeat="(k,x) in w">
                <ul data-ng-repeat="(k,y) in x" >
                    {{k}} : {{y}} 
                    <li ng-if="z.title" data-ng-repeat="(k,z) in y track by $index">
                        Title: {{z.title}} URL: {{z.URL}}
                    </li> 
                </ul> 
            </div>
       </div>
</div>

http://plnkr.co/edit/WLnXBQbbOqveJuHiUeEI?p=preview

I recommend making your hierarchy structure more explicit. For each menu, you can have a key "submenus" where you can find menus further down in the hierarchy. A useful directive for hiding elements is ng-show .

I would only build one complete menu tree and then set permissions for your users or roles. Otherwise the tree will become unmanageable and there will be repeated data.

Here is an example jsBin:

http://jsbin.com/sixiw/2/edit?html,js,output

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM