我的AngularJS模板包含一些自定义的HTML语法,如下所示:
<su-label tooltip="{{field.su_documentation}}">{{field.su_name}}</su-label>
我创建了一个指令来处理它:
.directive('suLabel', function() {
return {
restrict: 'E',
replace: true,
transclude: true,
scope: {
title: '@tooltip'
},
template: '<label><a href="#" rel="tooltip" title="{{title}}" data-placement="right" ng-transclude></a></label>',
link: function(scope, element, attrs) {
if (attrs.tooltip) {
element.addClass('tooltip-title');
}
},
}
})
一切正常,除了attrs.tooltip
表达式,它总是返回undefined
,即使在执行console.log(attrs)
时在Google Chrome的JavaScript控制台中可以看到tooltip
属性。
有什么建议吗?
更新: Artem提供了一个解决方案。它包括这样做:
link: function(scope, element, attrs) {
attrs.$observe('tooltip', function(value) {
if (value) {
element.addClass('tooltip-title');
}
});
}
AngularJS + stackoverflow =极乐
发布于 2013-01-04 00:47:55
尽管在您的特定场景中使用'@‘比使用'=’更合适,但有时我会使用'=‘,这样我就不必记得使用attrs。$observe():
<su-label tooltip="field.su_documentation">{{field.su_name}}</su-label>
指令:
myApp.directive('suLabel', function() {
return {
restrict: 'E',
replace: true,
transclude: true,
scope: {
title: '=tooltip'
},
template: '<label><a href="#" rel="tooltip" title="{{title}}" data-placement="right" ng-transclude></a></label>',
link: function(scope, element, attrs) {
if (scope.title) {
element.addClass('tooltip-title');
}
},
}
});
使用'=‘我们得到双向数据绑定,因此必须小心确保scope.title不会在指令中被意外修改。优点是在链接阶段定义了本地作用域属性(scope.title)。
https://stackoverflow.com/questions/11913841
复制相似问题