2017-01-13 107 views
3

我在ng-repeat指令中遇到了transclusion的问题。 Angular在模板中找不到.transclude元素,因此替换不会发生。我相信这是由于ng-repeat在截取时删除了.transclude这一事实造成的。我想知道如何在ng-repeat之前替换占位符或如何以任何其他方式解决此问题。ngRepeat中的Angular Directive Transclusion

旁注:如果我使用NG-transclude指令代替,那么代码是 工作正常,但后来我不得不使用$父 {{$ parent.item.name}}来访问值,这是我不喜欢。

这里是我的代码的版本缩小的:

HTML

<div mydir="items"> 
    {{item.name}} 
</div> 

template.html

<div ng-repeat="item in items"> 
    <div class="transclude"></div> 
</div> 

指令

app.directive("mydir" , function(){ 
    return { 
     templateUrl : "template.html", 
     transclude : true, 
     scope : { 
      items: "=mydir" 
     }, 
     link : function($scope , $element , attrs , $ctrl , $transclude){ 
      $transclude(function($content){ 
       $element.find(".transclude").replaceWith($content); 
      }); 
     }, 
    }; 
}) 

预期的结果之前,编译

<div mydir="items"> 
    <div ng-repeat="item in items"> 
     {{item.name}} 
    </div> 
</div> 
+0

添加一些更多的上下文,你试图完成什么?这将有助于您指向其他解决方案。 –

回答

0

这里是一个选择,我认为将让你你要去哪里。基本上,它会抓取你的html指令{{ item.name }}的内容,并在指令的编译函数中建立一个动态模板。

var app = angular.module('plunker', []); 

app.directive("mydir" , ['$compile', '$templateRequest', function($compile, $templateRequest){ 
    return { 
     scope : { 
      items: "=mydir" 
     }, 
     compile: function($element) { 
      var transclude = $element.html(); 
      $element.html(''); 
      return function(scope, elem) { 
       $templateRequest("template.html").then(function(html){ 
        var tpl = angular.element(html); 
        tpl.children('.transclude').append(transclude); 
        $compile(tpl)(scope); 
        elem.append(tpl); 
       }); 
      }; 
     } 
    }; 
}]); 

app.controller('MainCtrl', function($scope) { 
    $scope.items = [{ 
    name: "Item 1" 
    },{ 
    name: "Item 2" 
    }] 
}); 

这是demo

+0

我在网上看到了这些类型的解决方案,但事实上我加载模板而不是分配给变量,这使得它对我来说是不可行的。 – Tauri28

+0

使用'$ templateRequest'从文件加载它。 Plunker已更新。 –