我写了一个带有隔离范围的指令。

app.directive('myDirective', function() {
    return {
        restrict: 'E',
        scope {
            attr1: '@',
            attr2: '@',
            noValueAttr: // what to put here?
        },
        link: function(scope, elem, attrs) {
            // how to check here if noValueAttr is present in mark-up?
        }
    };
});

的HTML可能是
<my-directive attr1='...' attr='...' ... no-value-attr>

或者
<my-directive attr1='...' attr='...' >

我在想如何使用(并让指令检测是否存在)没有指定值的可选属性。谢谢。

最佳答案

只需在链接函数中使用attrs.hasOwnProperty('noValueAttr')即可测试该属性是否存在。

不要忘记标记中的属性将是no-value-attr,而不是您显示的noValueAttr

 link: function(scope, elem, attrs) {
           if (attrs.hasOwnProperty('noValueAttr'))
              // attribute is present
           else
              // attribute is not present

    }

09-25 19:53