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

查看:97
本文介绍了从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 前pression,它总是返回未定义例外,即使做了的console.log(ATTRS)当提示属性是从谷歌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).

任何建议?

更新:一种解决方案,通过提供阿尔乔姆了。它包括在做这个:

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 +计算器=幸福

AngularJS + stackoverflow = bliss

推荐答案

请参见属性从指令的文档。

观察插值属性的:使用$观察观察包含插补属性的值发生变化(例如SRC ={{栏}})。这不仅是非常有效的,但它也可以轻松地获得实际价值的唯一方式,因为在链接阶段插值尚未评估,因此该值,此时设置为undefined。

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天全站免登陆