M
M
MagNet2013-12-09 05:32:10
Angular
MagNet, 2013-12-09 05:32:10

How to make a dynamic menu in Angular?

Hello.
There is a menu:

меню1
    подменю1
    подменю2
    подменю3
    т.д
меню2
    подменю1
меню3

Initially, I load the top level elements (menu1, menu2, etc.), when the menu element is clicked, I load the child elements (ajax) and store them in menu1.children = [submenu here]. All the same is necessary for the submenu. The degree of nesting is unlimited.
Each menu element contains the following data:
id, name, parent_id, level There
will be approximately 200 - 250 elements. Nesting is most likely a maximum of 3 levels.
What is the best way to do this in angularjs? Maybe there is a better approach?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2013-12-09
@MagNet

If you are asking about rendering in html, then ng-include with a template will help you. A single item template can be stored directly in your view in a script.

<script type="text/ng-template" id="category.html">
   код элемента
</script>

In the right place (where the tree itself will be) we write:
<ul>
      <li ng:repeat="category in categories" ng:include="'category.html'"></li>
</ul>

categories is our main tree array.
"'category.html'" - there must be two quotes to return a string.
Inside the element code (in the template, that is) it will be necessary to write accordingly:
ID: {{category.id}}, 
NAME: {{category.name}}
<ul ng:if="category.children">
        <li ng:repeat="category in $parent.category.children" ng:include="'category.html'"></li>
       <!-- $parent нужен из-за ng-if -->
</ul>

As for the structure, everything is clear - an array with child elements is added to each element. When you click on the element, the loading will go on, the data will be added to the original array, it will be updated, and the html tree will be updated accordingly. Unless, of course, you load data using native methods that trigger redrawing, or use ($scope.$apply(fn))
I did exactly this in my projects (however, without reloading items - the trees were no more than 30 elements). If there is a better way, I'd love to hear about it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question