简体   繁体   中英

How to generate multilevel menu items programmatically in angularjs?

I am creating side menu bar which is generated programatically from json.

I have coded two level items but I hard coded two level ulLi items in html. But I don't want to hard coded the level of menu items.

I have tried the following code.

HTML

<ul class="sidebar-menu sidebar-nav" ng-repeat="m in modulos">
    <li class="treeview" ng-repeat="(itemIndex, item) in modulos">
        <a ng-click="showSubmenu(itemIndex)">
            <i class="fa fa-table"></i> <span>{{item.module}}</span>
        </a>

        <ul class="sub-nav" ng-show="isShowing(itemIndex)">
            <li ng-repeat="sub_element in m.submodule">
                <a href="{{sub_element.url}}">{{sub_element.res}}</a>
            </li>
        </ul>
    </li>
</ul>

js

$scope.modulos = [{
    "module":"Admin System ",
    "adm_modulo_id":1,
    "submodule": [{
        "res":"Angular","url":"#",
        "submodule":[{
            "res":"Angular",
            "url":"#/admin/1"
        },{
            "res":"Linux",
            "url":"#/admin/2"
        },{
            "res":"Server",
            "url":"#/admin/3"
        }]
    },{
        "res":"Linux",
        "url":"#/admin/2"
    },{ 
        "res":"Server",
        "url":"#/admin/3"
    }]

}];

Here I have coded two levels of items. But it is a variable. Some items will have 5 levels and another one will have 2 levels.

So based in submodule, I need to write a logic.

You do this with recursion like every other "tree" problem. Recursion in html with angular is done with the template in the html, example:

<script type="text/ng-template" id="list_node.html">
    ........
    <ul>
        <li ng-repeat="node in node.children" ng-include="list_node.html"></li>
    </ul>
</script>

On the place where the dots are in my snipper above, you will define what to show (what data on the node item). Example: <p>{{node.name}}</p>

And then in your ng-repeat you just include the template. Example:

<ul class="node-indented slide">
    <li ng-repeat="node in node.children" ng-include="'list_node.html'"></li>
</ul>

Adjust this example to your use case and it will work.

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