gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 04:56:20 26 4
gpt4 key购买 nike

我在指令 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com