带有ng-show的AngularJS子菜单

时间:2017-05-11 17:07:54

标签: angularjs angularjs-directive ng-show

我制作了一个包含菜单项的指令,其中一些菜单项中包含子菜单项。制定指令,以便当您单击菜单项时,它会打开其子菜单。我的问题是,当我点击一个菜单项时,它会打开它的子​​菜单,当我点击另一个菜单项时,它会打开它,所以我打开了两个子菜单。
当我单击菜单项并仅打开单击的菜单项子菜单时,我希望它关闭所有其他子菜单。我该怎么办?

我的HTML代码:

<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>

这是我的指令代码:

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;
         }

     }
 }
});

那么点击菜单项时我应该怎么做才能关闭其他子菜单?

1 个答案:

答案 0 :(得分:1)

由于您将menuItem包装在menu指令中,因此可以让它知道最后将哪个项目的名称传递给父作用域中的属性,如下所示:

app.directive('menu', function() {
return {
    restrict: "E",
    template: "<div ng-class='{ show: visible, left: alignment === \"left\", right: alignment === \"right\" }' ng-transclude></div>",
    transclude: true,
    scope: {
        visible: "=",
        alignment: "@"
    }
};
});

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

然后您可以将该值与ng-show一起使用以隐藏其他值:

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

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

  Side Menu item (If I click this I would like all the other submenus to close, this case should cover all the Side Menu items)
  <ul ng-show="activeItem === 'second'">
    <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>

我已使用这些更改更新了您的plunker。希望这会有所帮助。