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

rya*_*uyu 2 angularjs angularjs-directive

我正在编写一个角度指令来包装一些自定义下拉列表的逻辑.我的指令有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?
            }
        }
    }]);
Run Code Online (Sandbox Code Playgroud)

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

<dropdowns customer="customer" warehouse="warehouse"></dropdowns>
Run Code Online (Sandbox Code Playgroud)

如何判断客户和仓库是否已设置,但位置不是?最终我正在使用该信息来显示/隐藏相关的下拉菜单.我宁愿只检查这些绑定,而不是只添加另外几个绑定到我的隔离范围.

Twi*_*ron 5

您可以使用attrs参数.attrs参数将显示元素的所有属性中的原始值(除了双重curlies将首先解析其值).

//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 */}
Run Code Online (Sandbox Code Playgroud)

这是一个显示差异的jsfiddle.

https://jsfiddle.net/L2j4ecd8/