【问题标题】:How do I access an attribute's value in a directive?如何访问指令中的属性值?
【发布时间】:2013-03-11 15:03:05
【问题描述】:

我正在尝试将模型绑定到指令中的属性。

Javascript --

function Main($scope) {
    $scope.text = "abc"
};

angular.module("myApp", [])
.directive("load", function ($compile) {
    return {
        restrict: 'E',
        replace: true,
        link: function (scope, element, attrs) {
           console.log(attrs);
           element.html(someFunction(attrs.text));
        }
    };
});

HTML --

<div ng-controller="Main">
    <load text="Hello {{text}}"></load>
</div>

您可以找到 jsFiddle here。在小提琴中,我取消了someFunction

【问题讨论】:

  • 您的问题是什么,您到底想完成什么?
  • 如果你想要指令中的范围,它已经在链接函数中作为'scope.text'。
  • demo 无法使用,因为您没有包含 Angular 库

标签: javascript angularjs angularjs-directive


【解决方案1】:

这里是一个快速的 plunk,显示了从指令中获取范围的 5 种不同方法。最后一个就是你要的那个:http://plnkr.co/edit/e2mMAq

【讨论】:

  • 如果我想用element.text() 值做同样的解析,我该怎么做?
  • 我没有遵循您所说的“分辨率”。你想要元素中文本的值吗?
  • &lt;div templated&gt;&lt;/div&gt; 就足够了 -- 不需要"{{text}}" 的属性值。
  • 仅供参考,您的最后一个示例也可以使用 scope.$watch 而不是 attrs.$observe (+1 BTW)。
【解决方案2】:

根据我认为您正在尝试做的事情,您需要进行两项修改:

  1. 您已将 replace 设置为 true,因此您可能应该在代码中添加一个模板,以用您的新标记替换元素。

  2. 在链接阶段发生时,插值尚未评估,因此您需要观察属性以寻找变化。

      angular.module('myApp', [])
          .directive('load', function($compile) {
              return {
                  restrict: 'E',
                  replace: true,
                  link: function (scope, element, attrs) {
                      console.log(attrs);
                      element.html(attrs.text);
    
                      attrs.$observe('text', function(value) {
                          console.log('new value = ' + value);
                          element.html(value);
                      });
                  }
    
              };
          });
    

查看observing interpolated attributes 部分了解更多详情。

【讨论】:

    猜你喜欢
    • 2019-06-08
    • 2017-06-18
    • 1970-01-01
    • 2012-08-08
    • 2016-03-26
    • 2021-09-30
    • 2016-10-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多