Javascript 在angular指令中获取原始转包内容
我的目标是创建一个Javascript 在angular指令中获取原始转包内容,javascript,angularjs,transclusion,Javascript,Angularjs,Transclusion,我的目标是创建一个editable指令,允许用户编辑属性附加到的任何元素的HTML(请参见Plunker:) 这几乎是可行的,除了我无法获得转写内容的原始HTML来初始化文本区域。我可以从clone.text()中获取它的文本,但它缺少HTML标记,如,,等等。因此,单击应用而不进行编辑不是幂等的 方法clone.html()抛出错误,无法读取未定义的属性“childNodes” app.directive("editable", function($rootScope) { return
editable
指令,允许用户编辑属性附加到的任何元素的HTML(请参见Plunker:)
这几乎是可行的,除了我无法获得转写内容的原始HTML来初始化文本区域。我可以从clone.text()
中获取它的文本,但它缺少HTML标记,如
,
,等等。因此,单击应用而不进行编辑不是幂等的
方法clone.html()
抛出错误,无法读取未定义的属性“childNodes”
app.directive("editable", function($rootScope) {
return {
restrict: "A",
templateUrl: "mytemplate.html",
transclude: true,
scope: {
content: "=editContent"
},
controller: function($scope, $element, $compile, $transclude, $sce) {
// Initialize the text area with the original transcluded HTML...
$transclude(function(clone, scope) {
// This almost works but strips out tags like <h1>, <div>, etc.
// $scope.editContent = clone.text().trim();
// this works much better per @Emmentaler, tho contains expanded HTML
var html = "";
for (var i=0; i<clone.length; i++) {
html += clone[i].outerHTML||'';}
});
$scope.editContent = html;
$scope.onEdit = function() {
// HACK? Using jQuery to place compiled content
$(".editable-output",$element).html(
// compiling is necessary to render nested directives
$compile($scope.editContent)($rootScope)
);
}
$scope.showEditor = false;
$scope.toggleEditor = function() {
$scope.showEditor = !$scope.showEditor;
}
}
}
});
app.directive(“可编辑”,函数($rootScope){
返回{
限制:“A”,
templateUrl:“mytemplate.html”,
是的,
范围:{
内容:“=editContent”
},
控制器:函数($scope、$element、$compile、$transclude、$sce){
//用原始转置的HTML初始化文本区域。。。
$transclude(功能(克隆,范围){
//这几乎可以工作,但去掉了标签,如,等等。
//$scope.editContent=clone.text().trim();
//这比@Emmentaler更有效,因为它包含扩展的HTML
var html=“”;
对于(var i=0;i,$element.innerHTML
应该包含原始HTML。我显示它包含
<div class="editable">
<span class="glyphicon glyphicon-edit" ng-click="toggleEditor()"></span>
<div class="editable-input" ng-show="showEditor">
<b><p>Enter well-formed HTML content:</p></b>
<p>E.g.<code><h1>Hello</h1><p>some text</p><clock></clock></code></p>
<textarea ng-model="editContent"></textarea>
<button class="btn btn-primary" ng-click="onEdit()">apply</button>
</div>
<div class="editable-output" ng-transclude=""></div>
</div>
clone
是元素的集合。您能在调试器中检查它吗?啊哈!迭代它们并附加outerHTML更接近:var text=”“;for(var i=0;iI怀疑可能是这样。很好。原始HTML可能位于外部作用域中的$element对象中。转换不是我的强项。为什么不在元素中包装原始内容,并使用一个类来查找它并将其隔离在一个容器中?如果是我,只需添加textarea/editor即可按需添加,如doubleclcik。需要时追加。非常有用。其中包含模板文本。您的回答确实激发了我添加方法compile(元素,attrs)
在其innerHTML
中包含转换后的HTML。但它是在Angular使用模板将其扩展为新的DOM元素后生成的。如果任何子元素都有replace:true
或转换内容本身,则会出现这种情况。我怀疑Angular无法在Angular处理之前生成HTML,因此开始的内容需要通过属性或ajax来传递,而不是通过转换来引导。这进入了摘要周期的核心。通过设置任意高的优先级,您可能能够确保首先对其进行计算。如果使用replace:true
带模板。表示元素
不包含原始原始原始内容,因为元素
是模板元素而不是原始元素