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 web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
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)