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!

Series Navigation<< AngularJS Fun With ScopesAngular Intro to Modules, Services, Factories, and Filtering >>

2 thoughts on “Create an Easy AngularJS Menu

  1. Sorry for being picky.

    Rather than using padding, why not set the sub menu to absolute positioning, and just using top=height of the main menu, left=button width * index? You then get a menu that (should) lay over the content below it rather than push it down.

    Thank you for your great angular tips, I’m very excited about learning more of the framework.

    1. Thanks for the comment, Tim. I agree that absolute positioning would make a better site implementation.

      Glenn

Comments are closed.