angularjs test 3: transclude in controller

by Richard Hunter

HTML

<div ng-app="myApp" ng-controller="MyController">
  <h1>Angular experiment: manual transclusion from directive controller</h1>

  <rh-foo>
    <rh-bar></rh-bar>
  </rh-foo>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.8.3/angular.js" integrity="sha512-klc+qN5PPscoGxSzFpetVsCr9sryi2e2vHwZKq43FdFyhSAa7vAqog/Ifl8tzg/8mBZiG2MAKhyjH5oPJp65EA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<div>

</div>

CSS

.foo {
  background: hotpink;
  padding: 10px;
}

.foo .transcluded {
  background: lightgoldenrodyellow;
  padding: 10px;
}

JavaScript

angular.module('myApp', [])
  .controller('MyController', ['$scope', (scope) => {
    scope.title = 'inter directive communication';
  }])
  .directive('rhFoo', () => {
    return {
      transclude: true,
      template: `
      	<div class="foo">
        	<input ng-model="title"/>
        	<h2>foo: {{title}}</h2>
          <div class="transcluded"></div>
        </div>
      `,

      controller: ['$scope', '$transclude', '$element', function FooController(scope, transclude, element) {
      	console.log('Foo Controller')
        const container = element[0].querySelector('.transcluded');
    
        const transcluded = transclude();
        container.append(...Array.from(transcluded));
      }],
      compile: () => {
        console.log('Foo Compile');
        return {
          pre: () => {
            console.log('Foo PreLink');
          },
          post: () => {
            console.log('Foo PostLink');
          },
        };
      },
    }
  })
  .directive('rhBar', () => {
    return {
      restrict: 'AE',
      template: `<div>bar: {{title}}</div>`,
      controller: function BarController() {
        console.log('BarController')
        this.name = 'bar'
      },
      compile: () => {
        console.log('Bar Compile');
        return {
          pre: () => {
            console.log('Bar PreLink');
          },
          post: () => {
            console.log('Bar PostLink');
          },
        };
      },
    };
  })