【问题标题】:Accessing attributes from an AngularJS directive从 AngularJS 指令访问属性
【发布时间】:2012-08-08 11:23:17
【问题描述】:

我的 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) 时,在谷歌浏览器的JavaScript 控制台中可以看到tooltip 属性。

有什么建议吗?

更新:Artem 提供了一个解决方案。它包括这样做:

link: function(scope, element, attrs) {
  attrs.$observe('tooltip', function(value) {
    if (value) {
      element.addClass('tooltip-title');
    }
  });
}

AngularJS + stackoverflow = 幸福

【问题讨论】:

  • 这个answer 到另一个问题解释了如何在 AngularJS 中正确表达三元组。
  • 就是这样:“AngularJS + stackoverflow = bliss”

标签: angularjs angularjs-directive


【解决方案1】:

请参阅指令文档中的Attributes 部分。

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

【讨论】:

【解决方案2】:

虽然在您的特定场景中使用“@”比使用“=”更合适,但有时我使用“=”这样我就不必记住使用 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');
            }
        },
    }
});

Fiddle.

使用 '=' 我们得到双向数据绑定,因此必须注意确保指令中的 scope.title 不会被意外修改。优点是在链接阶段,定义了本地范围属性(scope.title)。

【讨论】:

  • 嘿,马克,您对使用这些解决方案有何看法,是否有针对使用双向数据绑定的链接属性使用观察的具体指南?我认为使用双向数据绑定看起来更干净,但我想知道是否有理由不使用它?
  • @Jeroen,我发布了关于使用 @= here 的更长讨论。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-25
  • 2017-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-26
相关资源
最近更新 更多