从 AngularJS 指令访问属性

我的 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 = 极乐

124371 次浏览

See section Attributes from documentation on directives.

observing interpolated attributes: Use $observe to observe the value changes of attributes that contain interpolation (e.g. src="\{\{bar}}"). Not only is this very efficient but it's also the only way to easily get the actual value because during the linking phase the interpolation hasn't been evaluated yet and so the value is at this time set to undefined.

Although using '@' is more appropriate than using '=' for your particular scenario, sometimes I use '=' so that I don't have to remember to use attrs.$observe():

<su-label tooltip="field.su_documentation">\{\{field.su_name}}</su-label>

Directive:

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');
}
},
}
});

Fiddle.

With '=' we get two-way databinding, so care must be taken to ensure scope.title is not accidentally modified in the directive. The advantage is that during the linking phase, the local scope property (scope.title) is defined.