3

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!

1 Answer 1

5

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
        });
    }
Sign up to request clarification or add additional context in comments.

5 Comments

Hmm yeah this makes sense, I don't know why it's not working...I would just reference it as <tr showpencilhover ng-repeat="user in users"> correct?
is Users initialized to your app? (var Users = angular.module("myApp") ?
sorry for the slow response, but yes, Users is initialized in the app
I created a test directive it see if it would even work, to ensure that its initializing, and it worked. I'm not sure why this solution isn't working. Here was the test directive: Users.directive('test', function() { return { restrict: 'A', link: function(scope, element, attrs) { element.on('mouseover', function() { console.log('test'); }); }}});
Also, when I console.log(scope.hoverEdit) undefined is returned

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.