7

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.

2 Answers 2

22

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

    }
Sign up to request clarification or add additional context in comments.

4 Comments

Do I need to place noValueAttr in the isolate scope? If it is, what would I place after the colon in noValueAttr: ...?
@menorah84: Nope. You don't have to
@menorah84 You don't need to place all attributes in the isolate scope definition object. I tend to keep all constant string valued attributes and boolean/no-value attributes out of it, myself. Just use attrs instead.
when attribute is present scope.attribName=true else scope.attribName=false provide the variable I need in my template. Thanks
0

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

1 Comment

I don't think this answers the question: How to map value-less attributes that are truthy if present and false if not present to a boolean $scope variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.