简体   繁体   中英

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!

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
        });
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM