# Angular dropdown menu

I've made a dropdown menu using angularJS, it works fine but I feel that I'm not following the DRY principle. Is there a way to combine this switch statement into something more efficient with less code? Instead of having 3 "cases" can I just use an OR operator inside of a data-ng-switch-when or something like that? This code will get bigger because it's quite a big project so code efficiency is key.

<ul id="main-menu">
<li data-ng-repeat="item in mainMenu" data-ng-switch on="item"><a href="{{item}}.php">{{item}}</a>

<ul data-ng-switch-when="Meddelanden">
<li data-ng-repeat="subitem in subMenu.messages"><a href="{{subitem}}.php">{{subitem}}</a></li>
</ul>

<ul data-ng-switch-when="Mina sidor">
<li data-ng-repeat="subitem in subMenu.myPages"><a href="{{subitem}}.php">{{subitem}}</a></li>
</ul>

<ul data-ng-switch-when="Verktyg">
<li data-ng-repeat="subitem in subMenu.tools"><a href="{{subitem}}.php">{{subitem}}</a></li>
</ul>

</li>
</ul>


Here's my controller containing the menu items:

onlinePlatform.controller('onlinePlatformCtrl', function ($scope) {$scope.mainMenu = ['Startsida', 'Nyheter', 'Meddelanden', 'Mina sidor', 'Forum', 'Kalender', 'Verktyg', 'Hjälp'],
$scope.subMenu = { messages: ['Inkorg', 'Skickat', 'Borttaget'], myPages: ['Mina kurser', 'Mitt schema', 'Klasslista', 'Anteckningar'], tools: ['Ladda ner Dreamspark produkter'] } });  ## 1 Answer Make your menus more uniform, then you won't have to do the ng-switch-ing. So something like $scope.menus = [
{
title: 'Startsida'
},
{
title: 'Messages',
items: ['Inkorg', ...]
},
{
title: 'My Pages',
items: ['Mina kurser', ...]
},
...
];


Then check whether you have the items field and if so, render the items:

<ul id="main-menu">
<li data-ng-repeat="menu in menus"><a href="{{menu.title}}.php">{{menu.title}}</a>
<ul ng-if="menu.items">
<li data-ng-repeat="subitem in menu.items"><a href="{{subitem}}.php">{{subitem}}</a></li>
</ul>
</li>
</ul>


It might be worthwhile to split the URLs from the titles as well.

This approach will break down somewhat at a point when the nesting level of your menu gets too deep, because you have to add more nested lists, but until then this will keep working.

• So in the HTML I would write isExist="items"? instead of the switch thing? – Chrillewoodz Nov 10 '14 at 15:11
• Yeah, I've updated with a sketch which should work. – ferada Nov 10 '14 at 15:18
• This works fantastic, thank you so much lad! Will be a lot easier to structure the entire thing now :) – Chrillewoodz Nov 10 '14 at 15:26
• Great tip about the URL thing also, that concerned me a bit as well. This approach also allows me to solve an annoying bug which occurred in the Jquery. – Chrillewoodz Nov 10 '14 at 15:32