首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >从AngularJS指令访问属性

从AngularJS指令访问属性
EN

Stack Overflow用户
提问于 2012-08-11 18:20:35
回答 1查看 123.2K关注 0票数 95

我的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)时在Google Chrome的JavaScript控制台中可以看到tooltip属性。

有什么建议吗?

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

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

AngularJS + stackoverflow =极乐

EN

回答 1

Stack Overflow用户

发布于 2013-01-04 00:47:55

尽管在您的特定场景中使用'@‘比使用'=’更合适,但有时我会使用'=‘,这样我就不必记得使用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)。

票数 25
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11913841

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档