【问题标题】:AngularJS : How can I transclude an element into a template that uses ng-repeat?AngularJS:如何将元素转换为使用 ng-repeat 的模板?
【发布时间】:2014-07-25 21:11:37
【问题描述】:

我有一个轮播指令,其中包含一些分块,用于将传入的 items 数组映射到元素结构数组的数组中,然后生成类似于以下伪代码的标记:

<array of arrays>

  <array of items>
    <item>
    <item>
  </array of items>

  <array of items>
    <item>
    <item>
  </array of items>

</array of arrays>

这个角度模板看起来像这样:

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

鉴于我的查看代码:

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

我希望被嵌入的元素绑定到最深的ng-repeatitem 对象

此处提供了带有简化测试用例的完整 Plunker:http://plnkr.co/edit/kYItcXV0k9KvnpiYx1iG

问题是我不能将ng-transclude 属性放在ng-repeat 中,并且(如Plunkr 中的carousel.js 指令文件所示)我似乎无法手动注入要嵌入的标记在指令的compile 步骤中使用transclude() 函数进入该位置。

任何想法都将不胜感激。

【问题讨论】:

    标签: javascript angularjs angularjs-directive transclusion


    【解决方案1】:

    在现有指令的链接函数中设置一个引用 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>
    

    Demo

    【讨论】:

    • 完美,完全按照我的需要工作,谢谢。但是有一个问题:您能解释一下为什么这有效,而不是在预编译步骤中使用 transclude 函数吗?我还是不太明白。
    • 其实是a bug,在最新的1.3测试版中已经修复。此解决方案是旧版本的解决方法。基本上,您不能在模板中使用嵌入的另一个指令中使用ng-transclude。解决方法之所以有效,是因为它将 transclude 函数存储在不受嵌套 transclusion-using 指令影响的变量中,并且它与 ng-transclude 执行相同的操作而不实际使用它。
    • 这是您使用最新测试版的 Plunker 的another fork。您会注意到它的工作原理与您最初预期的一样。
    • 太棒了,非常感谢您的解释,很高兴知道我至少在正确的轨道上 :)
    猜你喜欢
    • 2017-02-14
    • 2014-02-02
    • 2012-10-03
    • 1970-01-01
    • 1970-01-01
    • 2015-02-05
    • 2015-12-26
    • 2015-10-18
    相关资源
    最近更新 更多