转换时$ element.append()不附加

时间:2017-08-25 19:48:56

标签: angularjs directive angularjs-ng-transclude

据我了解,下面的代码应该每次使用不同的索引值渲染段落三次。相反,它只渲染最后一次翻译。这是怎么回事?

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 个答案:

答案 0 :(得分:2)

$ transcludeFn接受第二个参数,该参数接收应用了新范围的元素的克隆。你想在这个函数中使用克隆放入dom。您可以在此处详细了解:http://ng.malsup.com/#!/transclude-function或此处: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>