Is it possible to replace the element with ng-transclude
on it rather than the entire template element?
HTML:
<div my-transcluded-directive> <div>{{someData}}</div> </div>
Directive:
return { restrict:'A', templateUrl:'templates/my-transcluded-directive.html', transclude:true, link:function(scope,element,attrs) { } };
my-transcluded-directive.html:
<div> <div ng-transclude></div> <div>I will not be touched.</div> </div>
What I am looking for is a way to have <div>{{someData}}</div>
replace <div ng-transclude></div>
. What currently happens is the transcluded HTML is placed inside the ng-transclude
div element.
Is that possible?
The ng-transclude directive is used to mark the insertion point for transcluded DOM of the nearest parent that uses transclusion. Use transclusion slot name as the value of ng-transclude or ng-transclude-slot attribute.
The ng-transclude directive facilitates AngularJS to capture everything that is put inside the directive in the markup and use it somewhere in the directive's template.
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()); } };
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With