在ng-switch中使用ng-transclude

jon*_*bro 5 javascript angularjs angularjs-directive

我无法让ng-transclude在ng-switch-default指令中工作.这是我的代码:

指示:

.directive('field', ['$compile', function($complile) {
        return {
            restrict: 'E',
            scope: {
                ngModel: '=',
                type: '@',
            },
            transclude: true,
            templateUrl: 'partials/formField.html',
            replace: true
        };
    }])
Run Code Online (Sandbox Code Playgroud)

谐音/ 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>
Run Code Online (Sandbox Code Playgroud)

我称之为......

<field type="other" label="My field">
    test...
 </field>
Run Code Online (Sandbox Code Playgroud)

哪会产生错误:

[ngTransclude:orphan] Illegal use of ngTransclude directive in the template! No parent directive that requires a transclusion found.
Run Code Online (Sandbox Code Playgroud)

它在ng-switch指令之外毫无障碍地工作,但我对如何使其工作感到茫然.有什么建议?

编辑:这是一个现场演示:http://plnkr.co/edit/3CEj5OY8uXMag75Xnliq?p = preview

Bri*_*sio 6

问题是它ng-switch正在进行自己的转换.正因为如此,你的翻译会因为翻译而丢失ng-switch.

我认为你不能在ng-switch这里使用.

你可以使用ng-ifng-show代替:

<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>
Run Code Online (Sandbox Code Playgroud)


jon*_*bro 0

摘自:Github问题

问题是 ng-switch 也使用了嵌入,这导致了错误。

在这种情况下,您应该创建一个使用正确的 $transclude 函数的新指令。为此,请将 $transclude 存储在父指令的控制器中(在您的 case 字段中),并创建一个引用该控制器并使用其 $transclude 函数的新指令。

在你的例子中:

.directive('field', function() {
  return {
       ....
      controller: ['$transclude', function($transclude) {
        this.$transclude = $transclude;
      }],
      transclude: true,
       ....
  };
})
.directive('fieldTransclude', function() {
  return {
    require: '^field',
    link: function($scope, $element, $attrs, fieldCtrl) {
      fieldCtrl.$transclude(function(clone) {
        $element.empty();
        $element.append(clone);
      });
    }
  }
})
Run Code Online (Sandbox Code Playgroud)

在 html 中,您只需使用而<div field-transclude>不是<div ng-transclude>.

这是更新的插件:http://plnkr.co/edit/au6pxVpGZz3vWTUcTCFT ?p=preview