【发布时间】:2013-01-28 15:52:38
【问题描述】:
我写了一个指令,它有一个postLink,我编译了一些 html 代码并用 angularjs 渲染它。但问题是我无法从生成的 DOM 中获取 html 代码。
我的代码是:
app.directive("showResultAsText", ['$compile', function ($compile) {
return {
restrict: 'A',
compile: function compile(tElement, tAttrs, transclude) {
console.log('compile');
var watchModal = tAttrs["showResultAsText"];
var elem = jQuery(tElement);
var oriHtml = elem.html();
elem.empty();
return {
post: function postLink(scope, iElement, iAttrs, controller) {
scope.$watch(function () {
return scope.$eval(watchModal);
}, function (newVal) {
if (newVal) {
var s = $compile(angular.element(oriHtml))(scope);
console.log(s);
console.log(s[0]);
console.log(s[0].outerHTML);
console.log($('<div>').append(s[0]).html());
iElement.text(s[0].outerHTML);
}
});
}
}
}
}
}
你可以看到我使用console.log 来打印s 的值。在控制台中,它输出:
你可以看到console.log(s)和console.log(s[0])有很多信息,但是当我使用outerHTML时,里面的按钮都不见了。
我也尝试使用 jquery:jQuery(s[0]).html(),但同样的情况发生了。
将s 转换为 html 代码的正确方法是什么?
【问题讨论】:
-
你能解释一下为什么你需要编译的html代码吗?实际上请记住,
$compile服务不仅会生成 html,还会将事件绑定到元素等。因此,无论如何您都不能多次重复使用该 html。 -
我只想将生成的 html 显示为页面中的文本,我可以将其复制到其他地方。就像一个代码生成器
-
你能解释一下为什么你需要一个指令吗?如果不是绝对必要,那不是直接修改 DOM 的角度方式..
标签: angularjs angularjs-directive