hasAttribute()的AngularJS等效方法是什么?

7
在指令中,我想在对元素执行某些函数之前检查它是否具有某个属性。但是在 jqLite文档中没有找到任何相关内容。
例如:
.directive('noReadonly', function() {

    return {
      link: function($scope, $element, $attr, ctrl) {

        $element.on('focus', function() {
          if ($element.hasAttribute('readonly'))
          $element.removeAttr('readonly');
        });

      },
    }
  })

1
if (angular.isDefined($attr.readonly)) { … } - Blackhole
2个回答

10
< p > $attr 是一个带有属性的对象,您可以像平常一样使用它:

if($attr.hasOwnProperty("readonly"))

如评论中所提到的,这将检查属性是否存在。这个元素将导致一个true响应:

<input name="test" readonly>
如果你想检查真值,请扩展这个逻辑:
if($attr.hasOwnProperty("readonly") && $attr.readonly) {}
请注意,属性值被解析为字符串,因此$attr.readonly等于"true"(String),而不是true(Boolean)。

这个检查是检查它是否具有该属性,还是该属性的值已被定义? - Bryce Johnson
1
这会检查属性是否存在。 - azium
这在 link 上下文中有效。如何在 compile 上下文中使用它? - ganeshk
2
Angular 2 有相应的替代品吗? - mismas
如果有人正在寻找Angular2+的解决方案:https://stackoverflow.com/questions/62469060/angular-how-to-check-if-a-component-tag-has-specific-attribute-on-it - QmlnR2F5

1
if ($attr.readonly) {
   ...
}
else {
   //doesn't have it.
}   

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接