2

I've created a sub menu using angularjs.

Which will work fine for one sub menu, but I have multiple on the same page.

I'm trying to do this the "angular way" without using jQuery, which is proving difficult.

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

See code below.

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
  • 1
    Can't You maintain an array of values for subMenu ?? $scope.subMenu = [false, false, false] ??; Commented Aug 7, 2014 at 10:00

1 Answer 1

2

You can use an array for the submenu:

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

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

And for the 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>

Here is a demo.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.