I'm having trouble getting ng-transclude to work within an ng-switch-default directive. Here's my code:
Directive:
.directive('field', ['$compile', function($complile) {
return {
restrict: 'E',
scope: {
ngModel: '=',
type: '@',
},
transclude: true,
templateUrl: 'partials/formField.html',
replace: true
};
}])
partials/formField.html
<div ng-switch on="type">
<input ng-switch-when="text" ng-model="$parent.ngModel" type="text">
<div ng-switch-default>
<div ng-transclude></div>
</div>
</div>
I call it like so...
<field type="other" label="My field">
test...
</field>
Which produces the error:
[ngTransclude:orphan] Illegal use of ngTransclude directive in the template! No parent directive that requires a transclusion found.
It works without a hitch, outside of the ng-switch directive, I'm at a loss on how to get this working though. Any suggestions?
EDIT: Here's a live demo: http://plnkr.co/edit/3CEj5OY8uXMag75Xnliq?p=preview
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 document from http://docs.angularjs.org/guide/directive says: transclude - compile the content of the element and make it available to the directive. Typically used with ngTransclude. The advantage of transclusion is that the linking function receives a transclusion function which is pre-bound to the correct scope.
Essentially, transclusion in AngularJS is/was taking content such as a text node or HTML, and injecting it into a template at a specific entry point. This is now done in Angular through modern web APIs such as Shadow DOM and known as “Content Projection”.
The problem is that ng-switch
is doing its own transclusion. Because of this, your transclusion is getting lost with the transclusion of ng-switch
.
I don't think you will be able to use ng-switch
here.
You can use ng-if
or ng-show
instead:
<input ng-if="type == 'text'" ng-model="$parent.ngModel" type="{{type}}" class="form-control" id="{{id}}" placeholder="{{placeholder}}" ng-required="required">
<div ng-if="type != 'text'">
<div ng-transclude></div>
</div>
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