在其模板中使用Angular Directive属性 [英] Use Angular Directive attributes in its template
本文介绍了在其模板中使用Angular Directive属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在指令中使用属性的值?我的元素看起来像这样:
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(){
...
});
}
}
};
}
);
应该有三点的代码,但是我无法弄清楚如何将attrs对象(attrs.tooltipTitle
等)的内容放入该模板中.
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.
推荐答案
您可以拉出属性并将其放入指令的范围内,如下所示:
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');
});
}
}
};
});
这里是小提琴: http://jsfiddle.net/moderndegree/f3JL3/
这篇关于在其模板中使用Angular Directive属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文