user2516663
user2516663

Reputation:

Pass in Angular data-bound text to Bootstrap Tooltip title attribute

I am using Bootstrap tooltips on my page and I want to pass in text to the title attribute on it, using {{ }} but it doesn't work. Here's my HTML:

<a class="questionIcon" data-toggle="tooltip" data-placement="right" title="{{textBundle.tooltip-message}}">?</a>

I am initializing the tooltips in my controller like this:

$(function () {
    $('[data-toggle="tooltip"]').tooltip();
});

However, when I hover over the ?, the message that is displayed is: {{textBundle.tooltip-message}} and not the actual content. Is there a way to get the dynamic content to be inputted using the standard Bootstrap tooltip?

Upvotes: 1

Views: 1765

Answers (1)

jakeforaker
jakeforaker

Reputation: 1657

Agree with the comments... never, ever use jquery inside a controller. And you should use a directive. For example, my directive is called "aiTooltip", and here is how it leverages angular strap (http://mgcrea.github.io/angular-strap/#)

plunkr: http://plnkr.co/edit/DIgj8vnZFyKFtX6CjDHi?p=preview (something is awry with the placement, but you get the idea)

In your template:

    <p class="link" ai-tooltip="{{ name }}">{{ name }}</p>

And in the directive we inject the $tooltip service provided by angular-strap:

app.directive('aiTooltip', function aiTooltipDirective($rootScope, $timeout, $tooltip) {
        return {
            restrict: 'A',
            scope: {
                aiTooltip: '@', // text to display in caption
            },
            link: function aiTooltipLink(scope, elem, attrs) {
                var tooltip;

                $timeout(function() {
                    tooltip = $tooltip(elem, {
                        title: scope.aiTooltip,
                        html: true,
                        trigger: scope.aiTooltipTrigger|| 'hover',
                        placement: scope.aiTooltipPlacement || 'top',
                        container: scope.aiTooltipContainer || 'body'
                    });
                });
            }
        };
    });

And in the $scope of the template we pass in a scope variable called name

$scope.name = 'Foobar';

Upvotes: 1

Related Questions