Change class on mouseover in directive

前端 未结 4 1853
醉梦人生
醉梦人生 2020-12-12 19:31

I am having trouble working out how to get a class to change on a nested directive.

This is the outer ng-repeat

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-12 20:07

    I have run into problems in the past with IE and the css:hover selector so the approach that I have taken, is to use a custom directive.

    .directive('hoverClass', function () {
        return {
            restrict: 'A',
            scope: {
                hoverClass: '@'
            },
            link: function (scope, element) {
                element.on('mouseenter', function() {
                    element.addClass(scope.hoverClass);
                });
                element.on('mouseleave', function() {
                    element.removeClass(scope.hoverClass);
                });
            }
        };
    })
    

    then on the element itself you can add the directive with the class names that you want enabled when the mouse is over the the element for example:

    
    

    This should add the class hover and tint when the mouse is over the element and doesn't run the risk of a scope variable name collision. I haven't tested but the mouseenter and mouseleave events should still bubble up to the containing element so in the given scenario the following should still work

    providing of course that the li's are infact children of the parent div

提交回复
热议问题