我想有条件地使用ngAttr应用一个简单的指令。我不明白为什么总是显示我的指令。因此,如果我有一个未定义/错误的变量,我想应用我的指令:dirr。
当使用ngAttr时,将使用$ interpolate的allOrNothing标志,因此,如果插值字符串中的任何表达式导致undefined,则该属性将被删除而不添加到元素中。
<div ng-app="myApp" ng-controller="MainController" class="container-fluid">
<h2 ng-bind="currentVersion"></h2>
<hr>
<div ng-attr-dirr="hidden || undefined">Default div</div>
</div>
angular.module('myApp',[])
.directive('dirr', function(){
return {
restrict:'AE',
template:'<div>Div from directive</div>'
}
})
.controller('MainController',['$scope', function($scope){
$scope.currentVersion = 'Angular 1.3.6';
$scope.hidden = undefined;
}])
;
答案是正确的,并且您提供的示例代码适用于小问题,但是当在大型应用程序上解决此问题时,您可能希望采用这种方法:
<div ng-app="myApp" ng-controller="MainController" class="container-fluid">
<h2 ng-bind="currentVersion"></h2>
<hr>
<div dirr value="{{hidden}}">Default div</div>
</div>
.directive('dirr', function($log){
var directiveInstance = {
restrict:'AE',
scope:{
value:'@'
},
link: function (scope, element, attrs, ctrl) {
if(attrs.value === 'true'){
console.log('directive on !!');
$log.debug('element',element);
element[0].innerHTML = '<div>hello ' + attrs.value + '</div>';
}
else {
console.log('directive off !!');
}
}
}
return directiveInstance;
})
这样比较整洁,当您遇到类似以下情况时,您可能不想在单独的div中使用ngIf或ngSwitch指令复制代码:
<table>
<thead dirr value="{{statement}}">
<tr>
<th>
CrazyStuffHere...
</th>
<th>
CrazyStuffHere...
</th>
....
</tr>
</thead>
</table>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句