Maarten Maarten - 3 months ago 14
AngularJS Question

Use Angular Directive attributes in it's template

How can I use the value of an attribute in a Directive?
My element looks like this:

<div class="tooltip-icon" data-my-tooltip="click" data-tooltip-title="foo" data-tooltip-content="test content"></div>


I would like to use that in the template of my directive, which looks like this:

mainApp.directive('myTooltip',
function() {

// allowed event listeners
var allowedListeners = ["click"];

return {
restrict: 'A',
template: '<div class="tooltip-title">...</div>' +
'<div class="tooltip-content">' +
'...</div>',
link: function(scope, elm, attrs) {
if(allowedListeners.indexOf(attrs.myTooltip) != -1){
elm.bind(attrs.myTooltip, function(){
...
});
}

}
};
}
);


Where the tripple dots are there should be code, but I cannot figure out how to get the contents of the attrs object (attrs.tooltipTitle etc) into that template.

Answer

You can pull the attributes out and place them into the scope of the directive like this:

angular.module('myApp', []).
directive('myTooltip', function ($log) {
    // allowed event listeners
    var allowedListeners = ["click"];
    return {
        restrict: 'A',
        template:   '<div class="tooltip-title">{{tooltipTitle}}</div>' +
                    '<div class="tooltip-content">' +
                    '{{tooltipContent}}</div>',
        scope: {
            tooltipTitle: '@tooltipTitle',
            tooltipContent: '@tooltipContent'
        },
        link: function (scope, elm, attrs) {
            if (allowedListeners.indexOf(attrs.myTooltip) != -1) {
                elm.bind(attrs.myTooltip, function () {
                    $log.info('clicked');
                });
            }

        }
    };
});

Here is fiddle: http://jsfiddle.net/moderndegree/f3JL3/