3

I'm writing an angular directive to wrap up logic for some custom dropdowns. My directive has 3 dropdowns, any number of which may actually be used.

My directive (stripped down) looks like this:

app.directive('dropdowns',
    ['$http', '$filter', ...
    function($http, $filter, ...) {
        return {
            restrict: 'E',
            templateUrl: '/Some_template',
            scope: {
                customer: '=?',
                warehouse: '=?',
                location: '=?',
            link: function (scope, elm, attrs) { 

                //How do I tell if scope.customer is set to a binding?
            }
        }
    }]);

How do I check whether the dropdown bindings are actually bound to some other variable? To be clear, I can't check whether the variable is truthy because undefined values are fine. For example, if my HTML looks like this:

<dropdowns customer="customer" warehouse="warehouse"></dropdowns>

how can I tell that customer and warehouse are set, but location isn't? Ultimately I'm using that information to show/hide the relevant dropdowns. I'd rather just check these bindings instead of just adding another few bindings to my isolate scope.

1 Answer 1

6

You can use the attrs parameter for that. The attrs parameter will show you the raw values in all of the attributes of your element (with the exception that double curlies will have their values resolved first).

//create the dropdowns if the attribute was present
if(attrs.customer){ /* create the dropdown */}
if(attrs.warehouse){ /* create the dropdown */}
if(attrs.location){ /* create the dropdown */}

Here's a jsfiddle showing the differences.

https://jsfiddle.net/L2j4ecd8/

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

Comments

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.