我有一个 carousel 指令,其中包括一些分块,用于将传入的 items 数组映射到元素结构数组的数组中,然后生成类似于以下伪代码的标记:
<array of arrays>
<array of items>
<item>
<item>
</array of items>
<array of items>
<item>
<item>
</array of items>
</array of arrays>
这个 Angular 模板看起来像这样:
<div class="carousel__content" ng-style="carousel.containerWidth">
<ul class="carousel__chunk" ng-repeat="chunk in carousel.chunks" ng-style="carousel.chunkWidth">
<li class="carousel__item" ng-repeat="item in chunk" ng-style="carousel.itemWidth">
<div class="carousel__item-content">
[element should be transcluded into this spot.]
</div>
</li>
</ul>
</div>
鉴于我的 View 代码:
<!-- The <a> tag should appear inside the 'carousel.html' template's ng-repeat list. -->
<carousel items="items" config="config">
<a href="#">{{ item.name }}</a>
</carousel>
我希望嵌入的元素绑定(bind)到最深的 ng-repeat 的 item 对象
完整的 Plunker 和简化的测试用例可在此处获得:http://plnkr.co/edit/kYItcXV0k9KvnpiYx1iG
问题是我不能在 ng-repeat 中放置一个 ng-transclude 属性,并且那个(作为 carousel.js 指令Plunkr 显示中的文件)我似乎无法在 compile 步骤中使用 transclude() 函数将待嵌入标记手动注入(inject)到该位置指令。
任何想法将不胜感激。
最佳答案
在现有指令的链接函数中设置一个引用 transclude 函数的变量:
post: function($scope, $element, attrs) {
$scope.transclude = transclude;
...
然后,创建一个新指令来代替 ng-transclude 用于您希望嵌入的内容出现在其中的元素:
.directive('innerTransclude', function(){
return function(scope, elem, attrs){
scope.transclude(scope, function(clone){
elem.append(clone);
});
}
})
该指令只是将克隆附加到元素,同时避免了尝试在使用嵌入本身的元素内部使用嵌入的问题。不要忘记将它添加到您的模板中:
<div class="carousel__item-content" inner-transclude></div>
关于javascript - Angular : How can I transclude an element into a template that uses ng-repeat?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24050645/