获取角指令中原来transcluded内容 [英] Get original transcluded content within angular directive
问题描述
我的目标是创建一个编辑
指令,它允许用户修改该属性附加任何元素的HTML(见Plunker:的 http://plnkr.co/edit/nIrr9Lu0PZN2PdnhQOC6 )
My goal is to create an editable
directive that allows a user to edit HTML of any element to which the attribute is attached (see Plunker: http://plnkr.co/edit/nIrr9Lu0PZN2PdnhQOC6)
此的几乎的作品除了我不能得到transcluded内容的原始原始的HTML初始化文本区域。我可以从得到它的文本clone.text()
,但缺少像&LT的HTML标签,H1>
,< DIV>
等,所以点击没有编辑不适用幂等
This almost works except I can't get the original raw HTML of the transcluded content to initialize the text area. I can get the text of it from clone.text()
, but that's missing the HTML tags like <H1>
, <div>
, etc. so clicking apply with no edits is not idempotent.
该方法 clone.html()
抛出一个错误,无法读取的未定义的属性'子节点'
The method clone.html()
throws an error, 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;
}
}
}
});
(这个问题基本上是问题,code的早期尝试框架的问题,<一个经过重写批发href=\"http://stackoverflow.com/questions/20032347/get-original-transcluded-content-in-angular-directive\">Get在角指令原transcluded内容)
(This question is essentially a wholesale rewrite of the question and code after an earlier attempt to frame the question, Get original transcluded content in Angular directive)
推荐答案
的 $ element.innerHTML
应该包含原始的HTML。我显示,它包含
The $element.innerHTML
should contain the original HTML. I am showing that it contains
<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>
这篇关于获取角指令中原来transcluded内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!