Angularjs有多个子菜单

时间:2014-08-07 09:57:58

标签: javascript angularjs

我使用angularjs创建了一个子菜单。

哪个适用于一个子菜单,但我在同一页面上有多个。

我试图在不使用jQuery的情况下以“角度方式”执行此操作,这证明很难。

jsBin: http://jsbin.com/cimiw/3/edit

见下面的代码。

使用Javascript:

var myApp = angular.module('myApp', []);

    function MyCtrl($scope) {
        $scope.subMenu = false;

        $scope.toggleSubMenu = function () {
            $scope.subMenu = !$scope.subMenu;
        };
    }

HTML:

<div ng-controller="MyCtrl">
    <p>{{subMenu}}</p>
    <br>
  <ul>
        <li ng-class="{active: subMenu}"> <a href="#hello" ng-click="toggleSubMenu()">hello</a>

            <ul>
                <li>test</li>
                <li>test</li>
                <li>test</li>

            </ul>
        </li>
        <li> <a href="#foo" ng-click="toggleSubMenu()">foo</a>

            <ul>
                <li>bar</li>
                <li>bar</li>
                <li>bar</li>
            </ul>
        </li>
        <li> <a href="#bar" ng-click="toggleSubMenu()">bar</a>

            <ul>
                <li>foo</li>
                <li>foo</li>
                <li>foo</li>
            </ul>
        </li>
    </ul>
</div>

CSS:

ul > li {
    border: 1px solid blue;
}
ul > li > ul {
    border: 1px solid red;
    display: none;
}
ul > li.active > ul {
    display: block!important;
}

1 个答案:

答案 0 :(得分:2)

您可以将子阵列用于子菜单:

function MyCtrl ($scope) {
    $scope.subMenu = [];    // default is false

    $scope.toggleSubMenu = function (index) {
        $scope.subMenu[index] = !$scope.subMenu[index];
    };
}

对于HTML:

<ul>
    <li ng-class="{active: subMenu[0]}"> <a href="#hello" ng-click="toggleSubMenu(0)">hello</a>
        <ul>
            <li>test</li>
            <li>test</li>
            <li>test</li>
        </ul>
    </li>
    <li ng-class="{active: subMenu[1]}"> <a href="#foo" ng-click="toggleSubMenu(1)">foo</a>
        <ul>
            <li>bar</li>
            <li>bar</li>
            <li>bar</li>
        </ul>
    </li>
    <li ng-class="{active: subMenu[2]}"> <a href="#bar" ng-click="toggleSubMenu(2)">bar</a>
        <ul>
            <li>foo</li>
            <li>foo</li>
            <li>foo</li>
        </ul>
    </li>
</ul>

这是demo