【问题标题】:Convert compiled dom to html code in angularjs在angularjs中将编译的dom转换为html代码
【发布时间】: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


【解决方案1】:

如果你能提供一个 plunkr / jsFiddle-example 会更容易,但我想我知道出了什么问题。您被控制台愚弄了-当您执行console.log(s)时,它不会立即记录(它是异步的)-控制台获取对dom元素s [0]的引用,并且到了准备好打印角度完成了它的渲染。另一方面, s[0].outerHTML 和 s.html() 是同步的,所以你得到了预角渲染的结果。要解决这个问题,你可以做一个简单的 setTimeout:

setTimeout(function(){ console.log(s[0].outerHTML); });

Angular 现在应该有时间在回调之前进行渲染(我认为您不需要延迟,但我可能错了)。您还可以使用角度 $timeout-service 将回调函数与 $scope.$apply 一起包装 - 请参阅http://docs.angularjs.org/api/ng.$timeout

【讨论】:

    猜你喜欢
    • 2011-01-12
    • 1970-01-01
    • 2013-10-24
    • 1970-01-01
    • 2021-11-22
    • 2018-07-03
    • 1970-01-01
    • 2013-11-12
    相关资源
    最近更新 更多