Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular directive check if optional binding is set in isolate scope

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.

like image 767
ryanyuyu Avatar asked Nov 30 '25 02:11

ryanyuyu


1 Answers

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/

like image 192
TwitchBronBron Avatar answered Dec 02 '25 20:12

TwitchBronBron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!