Angular中ngRepeat指令下的指令传递

3
我有一个关于ng-repeat指令内的置换(transclusion)问题。Angular在模板中找不到.transclude元素,因此无法进行替换。我认为这是由于ng-repeat在置换时会删除.transclude元素导致的。我想知道如何在ng-repeat获取placeholder之前进行替换,或者以其他方式解决这个问题。
附注:如果我使用ng-transclude指令,则代码按预期工作,但是我必须使用$parent {{$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>

增加一些上下文,你想要实现什么?这将有助于指向其他解决方案。 - Mikko Viitala
1个回答

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"
  }]
});

这里是演示


我在网上看到过这种解决方案,但是由于我加载模板而不是分配给变量,所以它对我来说行不通。 - Tauri28
使用 $templateRequest 从文件中加载它。Plunker 已更新。 - Michael Sacket

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接