Mitch
Mitch

Reputation: 1394

AngularJS custom directive for mouseenter and mouseleave

I am trying to make a custom directive because the first solution I came up with worked, but it seemed messy.

When the tr element has mouseenter I want to show the pencil icon, and when mouseleave occurs the pencil icon should hide again.

First solution: (this worked)

<tr ng-mouseenter="hoverEdit = !hoverEdit" ng-mouseleave="hoverEdit = !hoverEdit" ng-repeat="user in users">
    <td>{{user.first_name}}</td>
    <td>{{user.last_name}}</td>
    <td>{{user.email}}</td>
    <td><i ng-show="hoverEdit" class="fa fa-pencil"></i></td>
    <td><button class="btn btn-danger" ng-click="delete(user)">Delete</button></td>
</tr>

I thought the ng-mouseenter and ng-mouseleave seemed to clutter up the tr element, so I want to create a directive...here is what I tried

directive solution (doesn't work)

Users.directive('showpencilhover', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            element.on('mouseenter', function() {
                hoverEdit == !hoverEdit
            });

            element.on('mouseleave', function() {
                hoverEdit == !hoverEdit
            });
        }
    }
});

I believe the problem is that I can't just reference hoverEdit, so I'm not sure how to make this work. Thanks for any advice!

Upvotes: 3

Views: 2357

Answers (1)

tymeJV
tymeJV

Reputation: 104775

Sure you can, you just have to preface it with scope (notice how scope is injected in the link function)

link: function(scope, element, attrs) {
        element.on('mouseenter', function() {
            scope.hoverEdit == !scope.hoverEdit
        });

        element.on('mouseleave', function() {
            scope.hoverEdit == !scope.hoverEdit
        });
    }

Upvotes: 5

Related Questions