$element.append() not appending when transcluded

135 views Asked by At

As far as I understand, the below code should render the paragraph three times with a different index value each time. Instead it's only rendering the last transclusion. What's going on here?

const app = angular.module('app', [])
app.component('test', {
  transclude: true,
  controller: function($scope, $element, $transclude) {
    //The transclusion should appear 3 times right? Since we're appending 3 times?
    for(let index of [10, 11, 12]) {
      const x = $transclude(Object.assign($scope.$new(true), {index}))
      $element.append(x)
    }
  },
});
angular.bootstrap (document.querySelector('body'), ['app'])
<body>
  <test>
    <p>This is {{index}}</p>
  </test>
  <script src="https://code.angularjs.org/1.5.8/angular.js"></script>
</body>

1

There are 1 answers

0
Justin Obney On BEST ANSWER

$transcludeFn accepts a 2nd parameter that receives a clone of the element with the new scope applied. You want to use the clone in this function to put into the dom. You can read more about it here: http://ng.malsup.com/#!/transclude-function or here: https://docs.angularjs.org/api/ng/service/$compile#-controller-

const app = angular.module('app', [])
app.component('test', {
  transclude: true,
  controller: function($scope, $element, $transclude) {
    //The transclusion should appear 3 times right? Since we're appending 3 times?
    for(let index of [10, 11, 12]) {
      $transclude(
        Object.assign($scope.$new(true), {index}),
        x => $element.append(x)
      )
    }
  },
});
angular.bootstrap (document.querySelector('body'), ['app'])
<body>
  <test>
    <p>This is {{index}}</p>
  </test>
  <script src="https://code.angularjs.org/1.5.8/angular.js"></script>
</body>