我的目标是创建一个editable
指令,允许用户编辑附加属性的任何元素的 HTML(请参阅 Plunker:http ://plnkr.co/edit/nIrr9Lu0PZN2PdnhQOC6 )
这几乎可以工作,除非我无法获得转入内容的原始原始 HTML 来初始化文本区域。我可以从中获取它的文本clone.text()
,但是缺少 HTML 标签,如<H1>
,<div>
等,因此单击应用而不进行编辑不是幂等的。
该方法clone.html()
抛出错误,Cannot read property 'childNodes' of undefined
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;
}
}
}
});
(这个问题本质上是在较早尝试构建问题之后对问题和代码的全面重写,在 Angular 指令中获取原始嵌入内容)