How to replace the element with ng-transclude

后端 未结 4 1156
名媛妹妹
名媛妹妹 2021-01-30 17:24

Is it possible to replace the element with ng-transclude on it rather than the entire template element?

HTML:

相关标签:
4条回答
  • 2021-01-30 17:31

    It's easy to create a ng-transclude-replace directive, here is a copycat of the original 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();
                              }
                          });
                      }
                  };
              }]);
    

    PS:you can also check this link to see the difference between the ng-transclude

    0 讨论(0)
  • 2021-01-30 17:34

    this works in Angular 1.4.9 (and prob earlier too)

    return {
          restrict: 'E',
          replace: true,
          template: '<span data-ng-transclude></span>',
          transclude: true,
          link: function (scope, el, attrs) .........
    }
    
    0 讨论(0)
  • 2021-01-30 17:37

    I think the best solution would probably be to create your own transclude-replace directive that would handle this. But for a quick and dirty solution to your example you could essentially manually place the result of the transclusion where you want:

    my-transcluded-directive.html:

    <div>
        <span>I WILL BE REPLACED</span>
        <div>I will not be touched.</div>
    </div>
    

    Directive:

    return {
        restrict:'A',
        templateUrl:'templates/my-transcluded-directive.html',
        transclude:true,
        link:function(scope,element,attrs,ctrl, transclude)
        {
             element.find('span').replaceWith(transclude());
        }
    };
    
    0 讨论(0)
  • 2021-01-30 17:38

    If you don't have to support IE and Edge you can use display:contents in your css. That will destroy the wrapper on the level of css.

    You can read more about this new display propertie here: https://css-tricks.com/get-ready-for-display-contents/

    Current browser support (hope to see Edge support in the future): https://caniuse.com/#feat=css-display-contents

    0 讨论(0)
提交回复
热议问题