I have a directive (a progressbar) which should have two possible states, one without any description and one with a label on the left side. It would be cool to simple use the transcluded content for this label.
Does anyone know how I can add a class to my directive depending whether a transclude content has been given or not?
So I want to add:
<div class="progress" ng-class="{withLabel: *CODE GOES HERE*}"> <div class="label"><span ng-transclude></span> <div class="other">...</div> </div>
Thanks a lot!
After release of Angular v1.5 with multi-slot transclusion it's even simpler. For example you have used component
instead of directive
and don't have access to link
or compile
functions. Yet you have access to $transclude
service. So you can check presence of content with 'official' method:
app.component('myTransclude', { transclude: { 'slot': '?transcludeSlot' }, controller: function ($transclude) { this.transcludePresent = function() { return $transclude.isSlotFilled('slot'); }; } })
with template like this:
<div class="progress" ng-class="{'with-label': withLabel}"> <div class="label"><span ng-transclude="slot"></span> <div class="other">...</div> </div>
Based on @Ilan's solution, you can use this simple $transclude function to know if there is transcluded content or not.
$transclude(function(clone){ if(clone.length){ scope.hasTranscluded = true; } });
Plnkr demonstrating this approach with ng-if to set default content if nothing to transclude: http://plnkr.co/hHr0aoSktqZYKoiFMzE6
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With