cachaito
cachaito

Reputation: 343

angular ng-repeat toggle menu element

I have menu filled with $http method

<ul class="nav">
    <li ng-repeat="(itemIndex, item) in menuItems.menu_items">
        <a ng-click="showSubmenu(itemIndex)" ng-href="{{item.link}}">{{item.title}}</a>
        <ul class="sub-nav" ng-show="isShowing(itemIndex)">
            <li ng-repeat="subItem in item.submenu">
                <a ng-href="{{subItem.link}}">{{subItem.title}}</a>
                <span>{{subItem.desc}}</span>
            </li>
        </ul>
    </li>
</ul>

And in controller

$scope.activeMenuIndex;
$scope.showSubmenu = function(item) {
    $scope.activeParentIndex = item;
}

$scope.isShowing = function(index) {
    return $scope.activeParentIndex === index;
};

Basically it works - click on menu element hides other elements and expands clicked one. The problem is when I click on opened menu element - it won't hide.

Maybe you know a better idea of ​​the solution, than my (incomplete) way?

Greetings!

Upvotes: 0

Views: 1193

Answers (2)

You need to add condition like this:

$scope.showSubmenu = function(item) {
    if($scope.activeParentIndex === item){
        $scope.activeParentIndex = "";
    }else{
        $scope.activeParentIndex = item;
    }
}

Upvotes: 2

Mike
Mike

Reputation: 1246

As @fliborn said, you can just put that logic in the showMenu. Or, for clarity, consider renaming showMenu(id) to toggleMenu(id) -- so it's more clear that it handles the closing case if you call it with an id that is active.

But, in either case, you'd do as @fliborn said and set the activeParentIndex to null if you toggle the id that is currently active.

From an Angular perspective, that's certainly a reasonable way to go (i.e. that's a good technical way to implement that behavior, if that's the behavior you want).

The other thing to consider is whether your approach is ideal from a UI perspective. Is it clear to your end users that they can click on the open one in order to close? If unclear, consider putting a "+" icon to the left side of all the inactive headers, and have a "-" show next to the active one (use ng-class if using glyphicons, or ng-show and ng-hide if you are just going to use text or graphics).

That way, when a user clicks to open a section, the "+" turns into a "-" as it opens up, and the user realizes that they can click on the header again to close it.

Upvotes: 1

Related Questions