Aviran Cohen Aviran Cohen -4 years ago 88
AngularJS Question

AngularJs Directive for Tooltip

I want to create a directive that shows Tooltip (from AngularJs Bootstrap UI) based on user is authorized or not.

It does the job well and add the required attributes

tooltip
and
tooltip-position

but the tooltip doesn't show up.

If i compare the element generated by my code and element that has a tooltip as normal html,
its identical except
class="ng-scope"
, adding this class manually doesn't help.

Here is my directive code:

proGamersApp.directive('registered', ['$rootScope', 'authService', function ($rootScope, authService) {
return {
restrict: 'A',
scope: true,
link: function ($scope, element, attrs) {
element.addClass('faded');

$rootScope.$watch('user.role', function (role) {
$scope.$apply(function () {
var accessLevel = routingConfig.accessLevels[attrs.accessLevel];
if (!authService.authorize(accessLevel)) {
element.attr('tooltip-placement', 'bottom');
element.attr('tooltip', 'Avaiable for registered users.');
} else
element.attr('tooltip-placement', 'bottom');
element.attr('tooltip', 'Avaiable for registered users.');
});
});
}
};
}]);


Any idea anyone?

Update 3
removed the '
$compile(element)
since it says its undefined function,
and changed the use of the $apply function. still getting '$digest already in progress' error.

New Code:

proGamersApp.directive('registered', ['$rootScope', 'authService', function ($rootScope, authService, $compile) {
return {
restrict: 'A',
scope: true,
link: function ($scope, element, attrs) {
element.addClass('faded');

$rootScope.$watch('user.role', function (role) {
var accessLevel = routingConfig.accessLevels[attrs.accessLevel];
if (!authService.authorize(accessLevel)) {
element.attr('tooltip-placement', 'bottom');
element.attr('tooltip', 'Avaiable for registered users.');
} else {
element.attr('tooltip', 'Avaiable for registered users.');
}

$scope.$apply(element);
});

}
};
}]);

Answer Source

Try using $compile like this:

proGamersApp.directive('registered', ['$rootScope', 'authService', '$compile', 
function ($rootScope, authService, $compile) { 
    return { 
        restrict: 'A', 
        scope: true, 
        link: function ($scope, element, attrs) { 
            element.addClass('faded');
            $rootScope.$watch('user.role', function (role) {
                var accessLevel = routingConfig.accessLevels[attrs.accessLevel];
                if (!authService.authorize(accessLevel)) {
                    element.attr('tooltip-placement', 'bottom');
                    element.attr('tooltip', 'Avaiable for registered users.');
                } else {
                    element.attr('tooltip', 'Avaiable for registered users.');
                }
                $compile(element.parent().contents())($scope);
            });
        }
    };
}]);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download