Ism*_*imi 94 angularjs angularjs-directive
我的AngularJS模板包含一些自定义HTML语法,如:
<su-label tooltip="{{field.su_documentation}}">{{field.su_name}}</su-label>
Run Code Online (Sandbox Code Playgroud)
我创建了一个指令来处理它:
.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');
}
},
}
})
Run Code Online (Sandbox Code Playgroud)
一切正常,除了attrs.tooltip表达式,它总是返回undefined,即使该tooltip属性在进行操作时可以从谷歌Chrome的JavaScript控制台中看到console.log(attrs).
有什么建议吗?
更新:Artem提供了一个解决方案.它包括这样做:
link: function(scope, element, attrs) {
attrs.$observe('tooltip', function(value) {
if (value) {
element.addClass('tooltip-title');
}
});
}
Run Code Online (Sandbox Code Playgroud)
AngularJS + stackoverflow =幸福
Mar*_*cok 25
尽管使用'@'比使用'='更适合您的特定场景,但有时我使用'='以便我不必记住使用attrs.$ observe():
<su-label tooltip="field.su_documentation">{{field.su_name}}</su-label>
Run Code Online (Sandbox Code Playgroud)
指示:
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');
}
},
}
});
Run Code Online (Sandbox Code Playgroud)
小提琴.
使用'='我们得到双向数据绑定,因此必须注意确保scope.title不会在指令中被意外修改.优点是在链接阶段,定义了本地范围属性(scope.title).
| 归档时间: |
|
| 查看次数: |
119999 次 |
| 最近记录: |