Angular directives: How to find out if you have transcluding content

When you have an Angular directive that transcludes content, you might want to do something in case there is no content inside your element, like showing some default content.

Unfortunately, you can not do something like <span ng-transclude>default goes here</span>. Angular will always empty that element's text, even if there is nothing to transclude.

But you can use your directive's link function. Here's some CoffeeScript for you:

    @app.directive 'myStuff', [->
      restrict: 'E'
      transclude: true
      
      template: """
                <div class="my-stuff">
                  <span ng-hide="transcluding">default goes here</span>
                  <span ng-transclude></span>
                </div>
                """
                
      link: (scope, element, attributes) ->
        scope.transcluding = $(element).find('[ng-transclude] *').length > 0
    ]
Arne Hartherz