Загрузите исходный транскодированный контент в директиву angular
Моя цель - создать директиву 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)
Ответы
Ответ 1
$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>