私の目標はeditable
、属性が付加された任意の要素の HTML をユーザーが編集できるようにするディレクティブを作成することです (Plunkr: 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 ディレクティブで元のトランスクルージョンされたコンテンツを取得します)