繁体   English   中英

ngRepeat中的角度指令转换

[英]Angular Directive Transclusion within ngRepeat

我在ng-repeat指令中有翻译问题。 Angular在模板中找不到.transclude元素,因此不会发生替换。 我相信这是因为ng-repeat在转换时删除了.transclude。 我想知道如何在ng-repeat获取占位符之前替换或如何以任何其他方式解决此问题。

旁注:如果我使用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>

这是一个选项,我认为可以让你到达目的地。 基本上,它抓取你的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"
  }]
});

这是演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM