I've written a directive with an isolate scope.
我已经用隔离范围编写了一个指令。
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?
}
};
});
the html could be
HTML可能是
<my-directive attr1='...' attr='...' ... no-value-attr>
or
要么
<my-directive attr1='...' attr='...' >
I am wondering how to use (and have the directive detect if it's there or not) an optional attribute which has no assigned value. Thanks.
我想知道如何使用(并使指令检测它是否存在)一个没有赋值的可选属性。谢谢。
2 个解决方案
#1
19
Just use attrs.hasOwnProperty('noValueAttr')
in the link function to test whether the attribute is present or not.
只需在链接函数中使用attrs.hasOwnProperty('noValueAttr')来测试属性是否存在。
Don't forget the attribute in markup would be no-value-attr
, not noValueAttr
like you showed.
不要忘记标记中的属性是no-value-attr,而不是像你所展示的noValueAttr。
link: function(scope, elem, attrs) {
if (attrs.hasOwnProperty('noValueAttr'))
// attribute is present
else
// attribute is not present
}
#2
0
I know it is an old question, but there is that way to:
我知道这是一个老问题,但有这样的方式:
link: function(scope, elem, attrs) {
scope.noValueAttr = scope.$eval(attrs.noValueAttr) || 'default value';
}
#1
19
Just use attrs.hasOwnProperty('noValueAttr')
in the link function to test whether the attribute is present or not.
只需在链接函数中使用attrs.hasOwnProperty('noValueAttr')来测试属性是否存在。
Don't forget the attribute in markup would be no-value-attr
, not noValueAttr
like you showed.
不要忘记标记中的属性是no-value-attr,而不是像你所展示的noValueAttr。
link: function(scope, elem, attrs) {
if (attrs.hasOwnProperty('noValueAttr'))
// attribute is present
else
// attribute is not present
}
#2
0
I know it is an old question, but there is that way to:
我知道这是一个老问题,但有这样的方式:
link: function(scope, elem, attrs) {
scope.noValueAttr = scope.$eval(attrs.noValueAttr) || 'default value';
}