Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically create a menu bar based on JSON using Angular Material?

I am trying to create a menu bar recursively using Angular Material Menu Bar directive, but the result is not being as expected. The best solution I have so far is to create a directive and call it recursively, like shown here: https://plnkr.co/edit/5pFmmD6K3qz5qolRifVA. Notice that there are two menu bars in this Plunker. The first is created with my recursive structure from a JSON and the second is written directly on the template. The problem with my solution happens when there are nested menus like "Lorem -> Dolor -> ...", as the nested menus are not being aligned correctly.

Inspecting the generated code on Chrome, I notice that the nested menu in the second menu bar (written directly on template) has some properties regarding its nest state:

<md-menu md-position-mode="cascade" 
    class="md-nested-menu md-menu ng-scope"
    md-nest-level="1">
...
</md-menu>

while the same menu in the first menu bar doesn't:

<md-menu ng-if="ctrl.isCompoundedMenuItem()" class="md-menu ng-scope">
...
</md-menu>

What can I do to fix this?


Just adding an information: I have already tried an approach using ng-include to create the menu bar, but the result was terribly worse.

like image 774
Frederico Pantuzza Avatar asked Aug 10 '16 13:08

Frederico Pantuzza


1 Answers

I was able to solve the problems with the menu behaviour by setting the attributes and classes mentioned in the question "manually" in the directive template, like this:

<md-menu ng-if="ctrl.isCompoundedMenuItem()"
         md-position-mode="cascade"
         class="md-nested-menu"
         md-nest-level="{{ ::nestLevel }}">

Where nestLevel is in the isolated scope and is incremented on every new level:

<md-menu-content class="md-menu-bar-menu md-dense">
   <my-menu-item ng-repeat="item in menu.items" menu="item"
                 nest-level="{{ ::(nestLevel + 1) }}"></my-menu-item>
</md-menu-content>

Starting by 1, naturally:

<md-menu-bar ...>
   ...
   <md-menu-content>
      <my-menu-item ng-repeat="item in menu.items" menu="item" 
                    nest-level="1"></my-menu-item>
   </md-menu-content>
</md-menu-bar>

The updated plunker can be seen here: https://plnkr.co/edit/QBjeR2hZFKsJ88Hl4ptG.

like image 58
Frederico Pantuzza Avatar answered Oct 15 '22 14:10

Frederico Pantuzza