【问题标题】:AngularJS doesn't execute in HTML inserted with document.write()AngularJS 不会在使用 document.write() 插入的 HTML 中执行
【发布时间】:2012-11-19 08:12:06
【问题描述】:

我想插入来自 JS 函数的 HTML,该函数在加载正文时执行。最初主体是空的。

这个 HTML 有 AngularJS 命令,但问题是 AngularJS 不解析 HTML。

<!doctype html>
<html ng-app>
    <head>
        <script>
            function loadHTML(){
                html = '<ul ng-controller="phoneCtrl"><li ng-repeat="phone in phones">{{phone.name}}<p>{{phone.snippet}}</p></li></ul><script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script'+'><script src="controllers.js"></script'+'>';
                document.write = html;
            }
        </script>
    </head>
    <body onload="loadHTML();" ></body>
</html>

controller.js的内容是:

function phoneCtrl($scope) {
    $scope.phones = [
    {
        "name": "Nexus S",
        "snippet": "Fast just got faster with Nexus S."
    },

    {
        "name": "Motorola XOOM™ with Wi-Fi",
        "snippet": "The Next, Next Generation tablet."
    },

    {
        "name": "MOTOROLA XOOM™",
        "snippet": "The Next, Next Generation tablet."
    }
    ];
}

【问题讨论】:

  • 我相信 document.write() 实际上会擦除整个页面,不仅是正文,还有 AngularJS 脚本。因此,即使他们会处理稍后添加的 HTML,它也没有机会。

标签: javascript angularjs


【解决方案1】:

onload 代码在 AngularJS 真正解析 DOM 之后执行。因此,要将它们捕获到 Angular 中,您必须使用 $compile。查看有关 $compile 如何工作的文档。

【讨论】:

猜你喜欢
  • 2016-02-23
  • 2010-09-08
  • 1970-01-01
  • 2019-05-10
  • 1970-01-01
  • 1970-01-01
  • 2018-03-21
  • 2012-04-11
  • 1970-01-01
相关资源
最近更新 更多