javascript - 在指令 Controller 中使用编译时,在模板中非法使用 ngTransinclude 指令

标签 javascript angularjs

我在指令 Controller 中使用编译来获取第一个指令元素并对其进行编译,然后将其用于其他目的我不想使用指令的链接方法,有没有办法消除此错误?

我已在 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

最佳答案

在 Controller 中进行编译之前,从元素中删除 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) {
            }
        }
    });

由于嵌入已经在指令的编译阶段完成,因此在 Controller 中编译时不再需要 ng-transclude 指令。

DEMO on JSFiddle

关于javascript - 在指令 Controller 中使用编译时,在模板中非法使用 ngTransinclude 指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42421195/

相关文章:

angularjs - 自定义 ng-options 选择外观

javascript - 如何使用canvasJs绘制图表?

javascript - 在 node.js 中为所需模块创建回调

javascript - Acrobat JavaScript

javascript - Angularjs:使用 ngChange 时如何获取列表中的项目?

angularjs - 动态 bootstrap ui 日期选择器

javascript - 如何解决移动 <LI> 流 jQTouch 移动 Web 应用程序上的跳跃问题 (iPhone JavaScript)

javascript - 触发 iframe 内 textarea 的 'change' 事件

javascript - 格式化 momentjs 日期时间

javascript - 如何实现url中带有问号的Angular js网站