从AngularJS指令访问属性

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 =幸福

Art*_*eev 83

请参阅指令文档中的属性部分.

观察插值属性:使用$ observe来观察包含插值的属性的值变化(例如src ="{{bar}}").这不仅非常有效,而且它也是轻松获得实际值的唯一方法,因为在链接阶段,插值尚未进行评估,因此此时的值设置为未定义.

  • 网址再次更改:https://docs.angularjs.org/api/ng/service/$compile#attributes (3认同)
  • URL现在更改为http://docs.angularjs.org/api/ng/service/$compile#Attributes (2认同)

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).