ContextMenu with AngularJS Directives

June 27, 2014

Directives are the building block of AngularJS. Up till now, I was an end user for directives. Beforehand, I had some small and unsuccessful trials. This time, I take my time to read blogs, books and watch videos and realized that there are several concepts to understand to fully comprehend directives. For me, the most important ones are linking, compiling, defining the scope of the directive and data binding. This meetup record by Misko Hevery, creator of AngularJS, explained all of those concepts clearly. About scopes, this blog should give you an idea. To understand the difference between text binding, one-way binding and two-way binding you shall refer to this blog. Nowadays, I'm reading this book to gain a deeper understanding of AngularJS directives. After all those reading, I feel ready to write a simple directive: Context Menu (right-click menu).

Best Approach for ContextMenu

Let's decide the behaviour of a context-menu. To design it, should I hide & show of an intially created div or append & remove a dynamically created element? I tried both and append & remove approach seemed to be the best one.

Hide & Show Approach

In hide & show approach, since the context menu is not a child of the clicked item, hiding context menu on mouseleave will prevent you from going into menu and when you try it will will disappear. You shall try at the JSFiddle below:

Append & Remove Approach

In this approached, the $scope.myContextDiv parameter defines the HTML of context menu. This parameter is sent to contextMenu directive. Context menu is linked to the right clicked element on right click. Note that, since context menu is dynamically appended to the element, it has to be $compiled first.

In the directive, we shall get the context menu by lScope.myContextDiv or if we write this way lScope[ lAttr.contextMenu ])(lScope), the directive becomes independent of parameter names.

If you want to check the click elements of context menu items, please open the developer console of you browser. When you click at item1 or item2, you can see the console output.

The JS Fiddle of this directive is given as follows:

Please, note that this shall not be the best way to develop a context menu with AngularJS. If you have suggestions for a better one, please do not hesitate to contact with me.

For the Turkish and a more detailed version of this article please refer to this blog post.