等效于hasAttribute()的AngularJS? [英] AngularJS equivalent for hasAttribute()?

查看:73
本文介绍了等效于hasAttribute()的AngularJS?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在指令中,我想在元素上执行某些功能之前检查元素是否具有属性.但是在 jqLit​​e文档中,我看不到有什么用.

In a directive, I want to check if an element has an attribute before I execute some function on it. But I don't see anything made for that in the jqLite docs.

例如:

.directive('noReadonly', function() {

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

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

      },
    }
  })

推荐答案

$attr是具有属性的对象,因此您可以像普通方法一样使用它:

$attr is a object with the attributes, so you can work with it like normal:

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

如注释中所述,这将检查该属性是否存在.该元素将导致真实的响应:

As mentioned in the comments, this checks that the property exists. This element would result in a true response:

<input name="test" readonly>

如果您还想检查真实值,则可以扩展逻辑:

If you want to also check for truthy values, you can extend the logic:

if($attr.hasOwnProperty("readonly") && $attr.readonly) {}

请注意,属性值被解析为字符串,因此$attr.readonly等于"true"(字符串)而不是true(布尔值).

Note that attribute values are parsed as strings, so $attr.readonly equals "true" (String) and not true (Boolean).

这篇关于等效于hasAttribute()的AngularJS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆