Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

javascript - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...