Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
78
rated 0 times [  82] [ 4]  / answers: 1 / hits: 27870  / 11 Years ago, thu, june 27, 2013, 12:00:00

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 triple 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.


More From » angularjs

 Answers
120

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/


[#77367] Wednesday, June 26, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rohan

Total Points: 403
Total Questions: 93
Total Answers: 105

Location: Trinidad and Tobago
Member since Mon, Jul 13, 2020
4 Years ago
;