从 AngularJS 指令访问属性 [英] Accessing attributes from an AngularJS directive

查看:26
本文介绍了从 AngularJS 指令访问属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 AngularJS 模板包含一些自定义的 HTML 语法,例如:

My AngularJS template contains some custom HTML syntax like:

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

我创建了一个指令来处理它:

I created a directive to process it:

.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,即使 tooltip 属性是可见的在执行 console.log(attrs) 时从 Google Chrome 的 JavaScript 控制台.

Everything works fine, at the exception of the attrs.tooltip expression, which always returns undefined, even though the tooltip attribute is visible from Google Chrome's JavaScript console when doing a console.log(attrs).

有什么建议吗?

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

UPDATE: A solution was offered by Artem. It consisted in doing this:

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

AngularJS + stackoverflow = 幸福

AngularJS + stackoverflow = bliss

推荐答案

属性来自指令文档.

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

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.

这篇关于从 AngularJS 指令访问属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆