如何用ng-transclude替换元素

Fra*_*isc 35 angularjs angularjs-directive

是否可以用它替换元素ng-transclude而不是整个模板元素?

HTML:

<div my-transcluded-directive>
    <div>{{someData}}</div>
</div>
Run Code Online (Sandbox Code Playgroud)

指示:

return {
    restrict:'A',
    templateUrl:'templates/my-transcluded-directive.html',
    transclude:true,
    link:function(scope,element,attrs)
    {

    }
};
Run Code Online (Sandbox Code Playgroud)

我-transcluded-directive.html:

<div>
    <div ng-transclude></div>
    <div>I will not be touched.</div>
</div>
Run Code Online (Sandbox Code Playgroud)

我正在寻找的是一种<div>{{someData}}</div>替代方式<div ng-transclude></div>.目前是什么情况是transcluded HTML放在里面ng-transcludediv元素.

那可能吗?

swe*_*ren 38

我认为最好的解决方案可能是创建自己的transclude-replace指令来处理这个问题.但是对于您的示例的快速而肮脏的解决方案,您基本上可以手动将结果的结果放在您想要的位置:

我-transcluded-directive.html:

<div>
    <span>I WILL BE REPLACED</span>
    <div>I will not be touched.</div>
</div>
Run Code Online (Sandbox Code Playgroud)

指示:

return {
    restrict:'A',
    templateUrl:'templates/my-transcluded-directive.html',
    transclude:true,
    link:function(scope,element,attrs,ctrl, transclude)
    {
         element.find('span').replaceWith(transclude());
    }
};
Run Code Online (Sandbox Code Playgroud)

  • 注意,如果有一些指令,你需要编译内容:`.replaceWith($ compile(transclude())(scope))` (6认同)

gog*_*out 29

创建ng-transclude-replace指令很容易,这里是原始的copycat ng-transclude.

directive('ngTranscludeReplace', ['$log', function ($log) {
              return {
                  terminal: true,
                  restrict: 'EA',

                  link: function ($scope, $element, $attr, ctrl, transclude) {
                      if (!transclude) {
                          $log.error('orphan',
                                     'Illegal use of ngTranscludeReplace directive in the template! ' +
                                     'No parent directive that requires a transclusion found. ');
                          return;
                      }
                      transclude(function (clone) {
                          if (clone.length) {
                              $element.replaceWith(clone);
                          }
                          else {
                              $element.remove();
                          }
                      });
                  }
              };
          }]);
Run Code Online (Sandbox Code Playgroud)

PS:你也可以查看这个链接,看看之间的区别ng-transclude