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');
});
},
}
})
$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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With