AngularJS:脚本标记在ng-include中不起作用

时间:2015-12-08 11:43:43

标签: angularjs dom

我有一个带有以下代码的文件index.html:

<div ng-include="'fragment-1.html'"></div>

fragment-1.html的代码:

<b>Inside Fragment 1</b>
<script type="text/javascript">
    alert("Inside Fragment 1");
</script>

当我将index.html加载到浏览器中时,输出为:

内部碎片1

DOM具有<script>标记但未显示警告。

我的假设:

因为DOM首先加载Angular模块,然后Angular检查并将数据(在本例中为fragment-1.html文件内容)绑定到视图(index.html),它只是添加了片段的元素DOM中的-1.html。要在fragment-1.html中执行JS,我们应该为它创建一个hack。我在这个解释中是对的吗?或者还有其他我可能遗失的东西?

3 个答案:

答案 0 :(得分:3)

我必须在加载Angular之前加载jQuery。解释在上面指定的链接中。说明:script not running in templateurl

要在父HTML文件中包含另一个部分HTML文件,还可以使用Angular指令,具体取决于具体情况。有关何时使用ng-include以及何时使用指令,请参阅此答案:https://stackoverflow.com/a/24172025/3132646

答案 1 :(得分:1)

你不需要破解。 Angular为您提供了一个简洁明了的解决方案,可以解决您希望使用代码实现的目标。

控制器

.controller('fragmentOneCtrl', function ($scope) {
    alert('"Inside Fragment 1"');
})

查看

<div ng-repeat="go in ['go', 'gogo']" ng-include="'includeThis'">

</div>

<script type="text/ng-template" id="includeThis">
    <div ng-controller="fragmentOneCtrl">

    </div>
</script>

答案 2 :(得分:0)

您可能希望在以html

注入资源之前使用$sce.trustAsHtml