AngularJS submenu in directive with ng-show

2019-09-15 09:39发布

问题:

I have made a directive for my sidenav. In my sidenav I have some elements that have submenu items under them. At the moment I can toggle only one element in the sidenav, but I need atleast 2-3 more. How should I implement it ?

My directive code:

menuItem.directive("menuItem", function() {
 return {
     restrict: "E",
     template: "<div ng-click='toggle($event)' ng-transclude></div>",
     transclude: true,
     scope: {
         hash: "@",
         show: '=',
     },
     link: function($scope) {
         $scope.toggle = function(e) {
            $scope.show = !$scope.show;
         }

     }
 }
 });

My html code:

<menu visible="leftVisible" alignment="left">
<menu-item hash="first" show="someVar">

    Side Menu item
    <ul ng-show="someVar">
        <li>
            <a>First submenu item</a>
        </li>
        <li>
            <a>First submenu item</a>
        </li>
    </ul>
</menu-item>
<menu-item hash="second" show="someVar">

    Side Menu item
    <ul ng-show="someVar">
        <li>
            <a >Second submenu item</a>
        </li>
        <li>
            <a >Second submenu item</a>
        </li>
    </ul>
</menu-item>
<menu-item hash="third">Side Menu item</menu-item>
</menu>

My goal is that I can open submenus individually with ng-show in the sidenav, any ideas how to do it?

回答1:

If you have a fixed list of menu items, you can use separate variables for each menu item, like this

<menu visible="leftVisible" alignment="left">
    <menu-item hash="first" show="menu1">

        Side Menu item
        <ul ng-show="menu1">
            <li>
                <a>First submenu item</a>
            </li>
            <li>
                <a>First submenu item</a>
            </li>
        </ul>
    </menu-item>
    <menu-item hash="second" show="menu2">

        Side Menu item
        <ul ng-show="menu2">
            <li>
                <a >Second submenu item</a>
            </li>
            <li>
                <a >Second submenu item</a>
            </li>
        </ul>
    </menu-item>
    <menu-item hash="third">Side Menu item</menu-item>
</menu>

In this case variable menu1 is responsible for visibility of the first item, menu2 - visibility of the second one, etc.

But if you are iterating over some array, you can use a specific field for each menu item.

<menu visible="leftVisible" alignment="left">
    <menu-item ng-repeat="item in items" hash="{{item.hash}}" show="item.show">
        {{item.title}}
        <ul ng-show="item.show">
            <li ng-repeat="subItem in item.items">
                <a>{{subItem.title}}</a>
            </li>
        </ul>
    </menu-item>
</menu>

In this case you use show field for each array item.