Bryce Johnson Bryce Johnson - 1 month ago 16x
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'))



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


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