【问题标题】:Angular Directive Transclusion within ngRepeatngRepeat 中的 Angular 指令嵌入
【发布时间】:2017-05-29 01:17:36
【问题描述】:

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

【问题讨论】:

  • 添加更多上下文,您到底想达到什么目的?这将有助于为您指明其他解决方案。

标签: javascript angularjs


【解决方案1】:

我认为这里有一个选项可以帮助您到达目的地。基本上,它会抓取您的 html 指令 {{ item.name }} 的内容,并在指令的 compile 函数中构建一个动态模板。

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

【讨论】:

  • 我在网上看到了这些类型的解决方案,但我加载模板而不是分配给变量的事实使我无法使用它。
  • 使用$templateRequest 从文件中加载它。 Plunker 已更新。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-01
  • 1970-01-01
  • 2018-07-06
  • 1970-01-01
  • 2017-02-27
相关资源
最近更新 更多