在指令控制器中使用compile时,在模板中非法使用ngTransclude指令

时间:2017-02-23 16:26:29

标签: javascript angularjs

我在我的指令控制器中使用compile获取第一个指令元素并编译它然后将其用于其他目的我不想使用我的指令的链接方法,无论如何都要摆脱这个错误?

我已在此JSFIDDLE中重现了该问题:

   var app = angular.module('app', []);
        app.directive('panel', function ($compile) {
            return {
                restrict: "E",
                replace: true,
                transclude: true,
                template: "<div><h1>handrouss</h1><div ng-transclude ></div></div>",
                controller: function($scope, $element) {
                    var el = $compile($element.find('div')[0])($scope); // <--- this causing the issue
                  $scope.handrouss = el.html();
                },
                link: function (scope, elem, attrs) {
                }
            }
        });
        app.directive('panel1', function ($compile) {
            return {
                restrict: "E",
                replace:true,
                transclude: true,
                template:"<div ng-transclude></div>",
                link: function (scope, elem, attrs) {
                    elem.children().wrap("<div>");
                }
            }
        });

HTML:

<div  data-ng-app="app">
    <panel1>
        <panel>
            <input type="text" ng-model="firstName" />{{firstName}}
        </panel>
        <input type="text" ng-model="lastname" />
    </panel

1 个答案:

答案 0 :(得分:1)

在编译控制器之前从元素中删除ng-transclude属性。

    app.directive('panel', function ($compile) {
        return {
            restrict: "E",
            replace: true,
            transclude: true,
            template: "<div><h1>handrouss</h1><div ng-transclude ></div></div>",
            controller: function($scope, $element) {
              var div = $element.find('div');
              //REMOVE ng-transclude attribute
              div.removeAttr('ng-transclude');
              var el = $compile(div[0])($scope);
              $scope.handrouss = el.html();
            },
            link: function (scope, elem, attrs) {
            }
        }
    });

由于已在指令的编译阶段完成了转换,因此在控制器中进行编译时不再需要ng-transclude指令。

DEMO on JSFiddle