Detecting if optional transcoded elements are used in AngularJS directive?

I have a directive set up in the style shown below; it allows for optional transcoded elements such as <dir-header>

and <dir-footer>

used in this example.

.js directive (partial)

module.directive('dir', function () {
    return {
        restrict: 'E',
        templateUrl: 'path/template.html',
        transclude: {
            'header': '?dirHeader',
            'footer': '?dirFooter'
        },
        link: function (scope, elem, attrs) {
            // do something
        }
    };
});

      

template.html

<div ng-transclude="header">
  <!-- Transcluded header will appear here -->
</div>

<div class="static-content">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</div>

<div ng-transclude="footer">
    <!-- Transcluded footer will appear here -->
</div>

      

Using

<dir>
    <dir-header>My Header</dir-header>
    <dir-footer>My Footer</dir-footer>
</dir>

      

Based on what I have, is there a way to determine if it is being used <dir-header>

? Can I access the content passed into it - in this case the string "My header"

- from the link function?


Some details on what I've done so far:

I have seen several discussions on this topic using style transclude: true

rather than transclude: {}

. Based on suggestions found in this research, I tried the following:

link: function (scope, elem, attrs, $transclude) {
    $transclude(function (clone) {
        console.log(clone);
    });
}

      

I couldn't fully understand how the clown works, but it appears to be a NodeList representing what has been rewritten. Unfortunately, the only useful information I get from this is length; clone.length

for my use case the above would be 3 (one for dir

, header

and footer

). If I delete footer

, the length is 2 and so on. However, there doesn't seem to be any data to differentiate the elements in the NodeList, so I can't figure out which transformed elements are being used, exactly how many.

Ultimately, I would like to set some styling conditions based on whether or not any particular excluded element is used.

+3


source to share


1 answer


isSlotFilled

function function transclude

will give you the desired result.

angular.module('App', [])
  .directive('dir', function () { 
    return {
        restrict: 'E',
        template: `
          <div ng-transclude="header"></div>
          <div class="static-content">
            Lorem ipsum dolor sit amet, consectetur adipiscing elit.
          </div>

          <div ng-transclude="footer">
        `,
        transclude: {
            'header': '?dirHeader',
            'footer': '?dirFooter'
        },
        link: function ($s, $el, $attrs, thisCtrl, $transclude) {
          console.log($transclude.isSlotFilled('header'))
          console.log($transclude.isSlotFilled('footer'))
        }
    };
  });

      



working plnkr

+2


source







All Articles