据我了解,下面的代码应该将该段落渲染三次,每次使用不同的索引值。相反,它仅渲染最后的嵌入。这是怎么回事?
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/