Reputation: 1128
I have a directive:
angular
.module('test')
.directive('multiButton', function () {
return {
restrict: 'E',
replace: true,
scope: {
disabled: '@'
},
template: '<div class="multi-button"><button ng-disabled={{disabled}}></button></div>'
});
The disabled scope attribute is optional, but I don't want to have "ng-disabled" stuff in my template when rendered if no disabled attribute was submitted.
Is this possible? And if so how?
Upvotes: 1
Views: 1251
Reputation: 4471
You can check if the attribute exists on link, and add the related (ngDisabled
) attribute if so:
angular.module('myApp',[])
.directive('multiButton', function () {
return {
restrict: 'E',
replace: true,
scope: {
disabled: '@?'
},
template: '<div class="multi-button"><button></button></div>',
link: function(scope, element, attr){
if(attr.disabled){
element.find('button').attr('ng-disabled', attr.disabled);
}
}
}
});
Demo Fiddle: http://jsfiddle.net/guv11rxq/
Now, as expected, <multi-button disabled="hello"></multi-button>
will result in:
<div class="multi-button"><button ng-disabled="hello"></button></div>
But without the optional attribute, <multi-button></multi-button>
, it will result in:
<div class="multi-button"><button></button></div>
Upvotes: 1
Reputation: 5482
You can do this by using ng-if
in your template:
template: '<div class="multi-button" ng-if="disabled != ''"><button ng-disabled={{disabled}}></button></div><div class="multi-button" ng-if="disabled === ''"><button></button></div>'
Upvotes: 1