Angular.js: The "Show on mouseenter, hide on mouseleave" Directive

von

Because of my recent posts on Angular.js one asked me if I could help him out with a directive which would show some buttons if he hovers a line of a list. In fact it is not a list actually but some kind of nested divs, which are organized by Bootstrap. I told him this is actually pretty easy.

First let’s take a look on the HTML:

<div ng-repeat="entry in entries">
   <div> class="entry row-fluid">
      <div class="span2"></div>
      <div class="span2"></div>
      <div class="span2"></div>   
      <div class="span2" style="display:none" showonhoverparent>
         <span ng-click="deleteEntry(entry)"><a class="btn btn-danger" href="#">Delete</a></span>
      </div>
   </div>
</div>

What we can see here is a list of Bootstrap rows. They are generated one by one out of an array of entries. The last column is hidden. Now we can add a new directive to this element namely “showonhoverparent”. The goal is to show this column when somebody hovers the row. Inside the column are some action buttons, like in this case the delete button.

The Angular.js directive is straightforward:

var directives = angular.module('directives', []);
directives.directive('showonhoverparent',
   function() {
      return {
         link : function(scope, element, attrs) {
            element.parent().bind('mouseenter', function() {
                element.show();
            });
            element.parent().bind('mouseleave', function() {
                 element.hide();
            });
       }
   };
});

The name of the directive is “showonhoverparent” and matches the attribute in the HTML code. The “link” property of our creation object gets a new function which does the actual trick.

The element variable represents the html element which we have annotated - the column. With jQuerys parent() method we can select the enclosing tag and then bind a mouseenter/mouseleave event which shows or hides the column.

That’s all! The great benefit with Directives is we can create a set of them and reuse them all over our code.

Tags: #AngularJS #JavaScript #Open Source

Newsletter

ABMELDEN