Create an Easy AngularJS Menu

This entry is part 4 of 9 in the series: AngularJS Learning Series

My goal for this AngularJS experiment was to create a multi-level menu with a hide-away submenu, fed from an external data source. The sub-menu should appear when its parent is clicked. As with my other AngularJS examples, this turned out to be a very simple task involving minimal code.

[iajsfiddle fiddle=”f8ea6″ height=”200px” width=”100%” show=”result,html,js,css,resources” skin=”default”]

One directive in the example that I hadn’t used before was ngStyle which facilitates dynamic style assignment. I use it here to position the submenu under the appropriate parent item. The directive is assigned to the ul block, and when the parent item is clicked, a function is called that modifies the scoped ‘subLeft’ property, something like this:

<ul>
   <li ng-click="setStyle()">menu item</li>
</ul>
<ul ng-style="subLeft">
   <li>submenu item</li>
</ul>
$scope.setStyle = function() {
   $scope.subLeft = {'padding-left':'80px'};
}

One hurdle I had to overcome was that ng-click only takes an Angular expression, which does not use JavaScript eval() to evaluate. I wanted to send the id of the element that was clicked so I could derive its coordinates as a way of knowing where to place the submenu. Without the use of JavaScript I was unable to do that.

In the interest of keeping the example simple, I ended up sending the Angular iterator index instead of the element id. Since all of my menu items are the same width it was a matter of multiplying the index by that width to arrive at the correct positioning. Problem solved!