Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ng-transclude inside ng-switch

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

like image 410
jonnybro Avatar asked Nov 15 '13 10:11

jonnybro


People also ask

What does ng transclude do?

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.

What does Transclude mean in AngularJS?

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.

What is transclusion angular?

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”.


1 Answers

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>
like image 72
Brian Genisio Avatar answered Sep 29 '22 08:09

Brian Genisio