Bryce Johnson Bryce Johnson - 3 months ago 37
AngularJS Question

Angular 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');
});

},
}
})

Answer

$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).

Comments