如何在 angularjs 自定义指令的模板中获取属性值?

roo*_*oot 4 javascript angularjs

我正在尝试获取在 angularjs 中定义为自定义指令的“abc”的属性:

<div abc="user">
    Access granted!
</div>
Run Code Online (Sandbox Code Playgroud)

然后使用自定义指令更改 div 内的文本:

.directive('abc', function() {
  var attr;
  return {
    link: function (scope, element, attributes) {
      attr = attributes.abc;
      console.log(attr);
    },
    template: "" + attr
  };
});
Run Code Online (Sandbox Code Playgroud)

结果应该是 'user' 但它未定义,因为在执行模板时未定义 attr。那么,任何可能的帮助如何解决这个问题?

Mat*_*tin 5

您不能使用从属性加载的动态来编辑模板,您必须使用范围来更新您的模板

template: '<div> {{abc}} </div>', // here it's scope.abc
link : function (scope, elem, attr) {
    scope.abc = attr.abc;
}
Run Code Online (Sandbox Code Playgroud)