Check existence of attribute in AngularJs Directive

All we need is an easy explanation of the problem, so here it is.

Is is possible to check whether a given attribute is present in a directive, ideally using isolate scope or in a worst case scenario the attributes object.

With a directive that looked something like this <project status></project>, I want to conditionally render a status icon, but only if the status attribute is present.

return {
  restrict: 'AE',
  scope: {
    status: '@'
  },
  link: function(scope, element, attrs) {
    scope.status === 'undefined'
  }
}

Ideally, it would be bound straight to the scope, so that it could be used in the template. However, the bound variable’s value is undefined. The same goes for & read-only and = two-way bindings.

I know that it’s trivially solved by adding a <project status='true'></project>, but for directives that I will use frequently, I’d rather not have to. (XHTML validity, is not an issue).

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

The way to do this is to check for the existence of the attributes within the link function’s attrs parameter, and assign this to variables within your directive’s isolate scope.

scope:{},
link: function(scope, element, attrs){
  scope.status = 'status' in attrs;
},

This should work without having to use an if statement within your link function.

Method 2

The way to do what you want is by looking at the attribute object in the link function:

link: 
  function(scope, element, attrs) {
    if("status" in attrs)
       //do something
  }

Method 3

To Check for attributes when using angular 1.5+ components you can use the $postLink lifecycle hook and the $element service like this:

constructor(private $element) {}

$postLink() {
  if(!this.$element.attr('attr-name')){
    // do something
  }
}

Method 4

Since the attrs value is type of javascript object. To check attribute existence we can also using hasOwnProperty() method instead in keyword.

So, it could be :

link: function(scope, element, attrs) {
  var is_key_exist = attrs.hasOwnProperty('status');//Will return true if exist
}

You can read further the difference between in keyword and hasOwnProperty() method at this link

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply