Accessing attributes from an AngularJS directive
我的AngularJS模板包含一些自定义HTML语法,如:
1 | <su-label tooltip="{{field.su_documentation}}">{{field.su_name}}</su-label> |
我创建了一个指令来处理它:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | .directive('suLabel', function() { return { restrict: 'E', replace: true, transclude: true, scope: { title: '@tooltip' }, template: '<label></label>', link: function(scope, element, attrs) { if (attrs.tooltip) { element.addClass('tooltip-title'); } }, } }) |
一切正常,除了
有什么建议吗?
更新:阿耳特姆提供了一个解决方案。它包括这样做:
1 2 3 4 5 6 7 | link: function(scope, element, attrs) { attrs.$observe('tooltip', function(value) { if (value) { element.addClass('tooltip-title'); } }); } |
AngularJS+StackOverflow=极乐
请参阅指令文档中的属性部分。
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.
虽然使用"@"比在特定场景中使用"="更合适,但有时我使用"=",这样我就不必记住使用attrs.$observer():
1 | <su-label tooltip="field.su_documentation">{{field.su_name}}</su-label> |
指令:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | myApp.directive('suLabel', function() { return { restrict: 'E', replace: true, transclude: true, scope: { title: '=tooltip' }, template: '<label></label>', link: function(scope, element, attrs) { if (scope.title) { element.addClass('tooltip-title'); } }, } }); |
小提琴。
使用"="我们得到双向数据绑定,因此必须注意确保scope.title不会在指令中被意外修改。其优点是,在链接阶段,定义了本地作用域属性(scope.title)。