Attribute without value in AngularJS directive

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

I’ve written a directive with an isolate scope.

app.directive('myDirective', function() {
    return {
        restrict: 'E',
        scope {
            attr1: '@',
            attr2: '@',
            noValueAttr: // what to put here?
        },
        link: function(scope, elem, attrs) {
            // how to check here if noValueAttr is present in mark-up?
        }
    };
});

the html could be

<my-directive attr1='...' attr='...' ... no-value-attr>

or

<my-directive attr1='...' attr='...' >

I am wondering how to use (and have the directive detect if it’s there or not) an optional attribute which has no assigned value. Thanks.

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

Just use attrs.hasOwnProperty('noValueAttr') in the link function to test whether the attribute is present or not.

Don’t forget the attribute in markup would be no-value-attr, not noValueAttr like you showed.

 link: function(scope, elem, attrs) {
           if (attrs.hasOwnProperty('noValueAttr'))
              // attribute is present
           else 
              // attribute is not present

    }

Method 2

I know it is an old question, but there is that way to:

link: function(scope, elem, attrs) {
  scope.noValueAttr = scope.$eval(attrs.noValueAttr) || 'default value';
}

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