angularjs - $element.append() 嵌入时不追加

标签 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>

最佳答案

$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>

关于angularjs - $element.append() 嵌入时不追加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45888498/

相关文章:

javascript - 指令的依赖

javascript - 使用 'select' 元素在指令中包含自定义选项

即使不提交,AngularJS ng-submit 事件处理程序也会被调用

javascript - Angular - ngResource 打破了数据绑定(bind)

javascript - 使用所有对象属性键的 AngularJS ng-options

typescript - 实现 v-loading 指令,在加载数据时替换内容

javascript - 更改检测在 Angular 2 的指令事件输出中不起作用

没有 Controller 的Angularjs

javascript - AngularJS : Can't figure out why nested angular directive does not get rendered when transcluding with transclude :'element'

javascript - 编译嵌入模板