Read more

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

Arne Hartherz
July 31, 2014Software engineer at makandra GmbH

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.

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

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
    ]
Posted by Arne Hartherz to makandra dev (2014-07-31 15:32)