Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if a transclude content has been given for a angularjs directive

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!

like image 324
Sebastian Avatar asked Feb 04 '14 08:02

Sebastian


2 Answers

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> 
like image 148
Sergey Moiseev Avatar answered Oct 07 '22 15:10

Sergey Moiseev


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

like image 45
plong0 Avatar answered Oct 07 '22 14:10

plong0