gespinha
gespinha

Reputation: 8487

Check if directive has an attribute

I have the following code

<my-directive></my-directive>

and I want to evaluate the following trenary inside it:

{{ $scope.my-option ? 'YES' : 'NO' }}

like this:

<my-directive my-option></my-directive>

How can I do this? It should evaluate to true once I have the attribute, right? I've already binded the attribute with the = sign.

Upvotes: 0

Views: 394

Answers (2)

Christof Aenderl
Christof Aenderl

Reputation: 4512

In the case you don't have an isolated scope (and also works with isolated scope) you can check the attrs directly:

angular
.module('myModule')
.directive('myDirective', function($parse) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            var option;
            if (attrs.hasOwnProperty('myOption')) {
                // if attr is plain string
                option = attrs.myOption;
                // or parse from a scope property
                option = $parse(attrs.myOption)(scope);
            }
        }
    }
});

Upvotes: 1

Bruno Toffolo
Bruno Toffolo

Reputation: 1554

You shouldn't check for $scope.my-option here, but for $scope.myOption.

CamelCased attributes are only snake-cased in HTML code; they should be referenced using camelCase in all remaining JavaScript source.

So, your HTML tag should be like:

<my-directive my-option></my-directive>

But your AngularJS expression would be:

{{ $scope.myOption ? 'YES' : 'NO' }}

The $scope may not even be needed, what would reduce the expression to

{{ myOption ? 'YES' : 'NO' }}

Additionally, if you don't want to explicitly add the check as a watcher in your HTML, you may use the link function of your directive to do that. The documentation explains it in more detail.

In your directive, use it like the following snippet:

angular
    .module('myModule')
    .directive('myDirective', function() {
        return {
            restrict: 'A',
            scope: {
                myOption: '=?'
            },
            link: function(scope, element) {
                if (scope.myOption) {
                    // you have the attribute
                } else {
                    // you don't
                }
            }
        }
    });

Upvotes: 1

Related Questions