gpt4 book ai didi

javascript - 获取 Angular Directive(指令)中的原始嵌入内容

转载 作者:行者123 更新时间:2023-12-02 22:54:45 24 4
gpt4 key购买 nike

我的目标是创建一个editable指令允许用户编辑附加该属性的任何元素的 HTML(请参阅 Plunker: http://plnkr.co/edit/nIrr9Lu0PZN2PdnhQOC6 )

几乎有效,只是我无法获取嵌入内容的原始 HTML 来初始化文本区域。我可以从 clone.text() 获取它的文本,但是缺少像 <H1> 这样的 HTML 标签, <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;
}
}
}
});

(这个问题本质上是在之前尝试构建问题之后对问题和代码的大规模重写,Get original transcluded content in Angular directive)

最佳答案

$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>&lt;h1&gt;Hello&lt;/h1&gt;&lt;p&gt;some text&lt;/p&gt;&lt;clock&gt;&lt;/clock&gt;</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>

关于javascript - 获取 Angular Directive(指令)中的原始嵌入内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20102059/

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