Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS equivalent for hasAttribute()?

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.

e.g. :

.directive('noReadonly', function() {

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

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

      },
    }
  })
like image 490
Bryce Johnson Avatar asked May 15 '15 18:05

Bryce Johnson


1 Answers

$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) {}

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

like image 170
Mike Robinson Avatar answered Oct 13 '22 00:10

Mike Robinson