Angular 指令检查是否在隔离范围内设置了可选绑定

Angular directive check if optional binding is set in isolate scope

我正在编写一个 angular 指令来包装一些自定义下拉菜单的逻辑。我的指令有 3 个下拉菜单,实际上可以使用任意数量的下拉菜单。

我的指令(精简)如下所示:

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?
            }
        }
    }]);

如何检查下拉绑定是否实际绑定到其他一些变量?需要明确的是,我无法检查变量是否为真,因为未定义的值很好。例如,如果我的 HTML 看起来像这样:

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

我怎么知道客户和仓库已设置,但位置未设置?最终,我将该信息用于 show/hide 相关下拉菜单。我宁愿只检查这些绑定,而不是向我的隔离范围添加另外几个绑定。

您可以为此使用 attrs 参数。 attrs 参数将向您显示元素所有属性的原始值(双卷曲除外,它们的值将首先解析)。

//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 */}

这是一个显示差异的 jsfiddle。

https://jsfiddle.net/L2j4ecd8/