AngularJS不会在用document.write()插入的HTML中执行

时间:2012-12-01 05:04:12

标签: javascript angularjs

我想插入来自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."
    }
    ];
}

1 个答案:

答案 0 :(得分:3)

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