Class directive not working when using ng-class to

2019-06-21 20:50发布

I am trying to load a 'class' directive using ng-class. but my directive is never loaded when i do that. The directive is a multipurpose directive, and I don't want to create an isolated scope on this. it will be loaded only when required, based on ng-class conditions hence not using attribute or element directive. has anyone tried doing this and succeeded?

this directive is called using <div ng-class="someClass {{tooltip: enabled}}"></div> here enabled is a scope variable.

app.directive('tooltip', ['$timeout', '$location', '$rootScope', function (timer, $location, $rootScope) {
    return {
        restrict: 'C',
        transclude: true,
        link: function (scope, element) {
            var printContent = function () {
                /*  uses the content of .tooltip-content if it is a complex html tooltip, 
                    otherwise
                    you can use the title attribute for plaintext tooltips
                */
                var tooltipContent = $(element).find('.tooltip-content').html();
                if (!tooltipContent) {
                    tooltipContent = $(element).attr('title');
                }
                $(element).tooltip({
                    content: tooltipContent,
                    items: "img, a, span, button, div",
                    tooltipClass: "tooltip",
                    position: { my: "left+30 top", at: "right top", collision: "flipfit" },
                    show: { effect: "fadeIn", duration: "fast" },
                    hide: { effect: "fadeOut", duration: "fast" },
                    open: function (event, ui) { $rootScope.tooltipElement = event.target; }
                });
            };
            timer(printContent, 0);
        }
    };
}]);

1条回答
Melony?
2楼-- · 2019-06-21 21:30

Interesting issue. It seems that you don't want to use the ng-class directive since that doesn't recompile the content after adding the class. You'll likely want to create your own dynamic-class directive that actually recompiles when the value is true:

app.directive('dynamicClass', function($compile) {
    return {
        scope: {
            dynamicClassWhen: '=',
            dynamicClass: '='
        },
        link: function(scope, elt, attrs) {
            scope.$watch('dynamicClassWhen', function(val) {
                if (val) {
                    console.log(val);
                    elt.addClass(scope.dynamicClass);
                    $compile(elt)(scope);
                }
            });
        }
    };
});

You may need to modify this for the ability to remove the class and depending on if the $compile is sufficient for you or if you need to further manipulate the html, but this seems to be the right track for you. I made a fiddle with this in action.

Hope this helps!

查看更多
登录 后发表回答