AngularJS指令中没有值的属性
我已经编写了一个具有隔离作用域的指令AngularJS指令中没有值的属性,angularjs,angularjs-directive,Angularjs,Angularjs Directive,我已经编写了一个具有隔离作用域的指令 app.directive('myDirective', function() { return { restrict: 'E', scope { attr1: '@', attr2: '@', noValueAttr: // what to put here? }, link: function(scope, el
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>
或
我想知道如何使用(并让指令检测它是否存在)一个没有赋值的可选属性。谢谢。只需在link函数中使用attrs.hasOwnProperty('noValueAttr')即可测试属性是否存在 不要忘记标记中的属性是
no-value attr
,而不是像您所示的noValueAttr
link: function(scope, elem, attrs) {
if (attrs.hasOwnProperty('noValueAttr'))
// attribute is present
else
// attribute is not present
}
我知道这是一个老问题,但有一种方法可以:
link: function(scope, elem, attrs) {
scope.noValueAttr = scope.$eval(attrs.noValueAttr) || 'default value';
}
是否需要将
noValueAttr
置于隔离范围内?如果是,我会在noValueAttr:…
中的冒号后面放置什么?@menorah84:no。你没有to@menorah84您不需要将所有属性都放置在隔离范围定义对象中。我倾向于将所有常量字符串值属性和布尔值/无值属性排除在外。只需使用attrs
即可。当属性存在时scope.attribName=true
elsescope.attribName=false
在模板中提供所需的变量。Thanks我不认为这回答了问题:如何将存在时为真、不存在时为假的无值属性映射到布尔$scope变量。
link: function(scope, elem, attrs) {
scope.noValueAttr = scope.$eval(attrs.noValueAttr) || 'default value';
}