在AngularJS中,HTML模板中包含的任何内联JavaScript代码都不起作用。
例如:
main.html文件:
<div ng-include="'/templates/script.html'"></div>
和script.html文件:
<script type="text/javascript">
alert('yes');
</script>
当我打开主页时,我希望一条警报消息说"是",但什么也不会发生。我认为AngularJS中的某些安全限制正在阻止内联脚本,但我找不到任何解决方法。
注意:我不使用jQuery或任何其他框架,只有Angularjs 1.2.7。
jqlite不支持脚本标签。jQuery确实这样做,因此建议在需要此功能的情况下包括jQuery。
来自Angular的Igor Minar在此讨论中:
我们研究了jqlite中的支持脚本标签,但是需要的是 完成跨浏览器的支持涉及很多黑魔法。为了 这个原因我们决定现在我们只是推荐 在这种特殊情况下,用户将jQuery与Angular一起使用。它 对于我们来说,重写三分之一的jQuery来获得这是没有意义的 在jqlite中工作。
这是相关的github问题jqlite应该以与jQuery相同的方式创建元素,在此之前,igor总结了此问题,然后以此:
这对jqlite来说太疯狂了,所以我们不会这样做。 相反,我们要记录一下,如果您想要脚本元素 在ng中:包括或ng:查看模板,您应该使用jQuery。
jQuery的演示plunker
Angular使用ng-include
指令上删除脚本的$ Sanitize。模板的更好方法是为该模板创建控制器。
最好将单个控制器用于模板。
在template.html
中<form role="form" ng-controller="LoginController">
<input type="text" placeholder="Email" ng-model="email">
<input type="password" placeholder="Password" ng-model="password">
<button class="btn btn-success" ng-click="login()">Sign in</button>
</form>
在LoginController
中,您可以使用您想要的任何代码
angular.module('myApp.controllers', []).
controller('LoginController', [function() {
alert('controller initialized');
}])
当ng-include
添加内容为 $includeContentLoaded
时触发的事件。您的脚本应包括在此事件中:
例如(拔出演示):
function SettingsController($scope, $window) {
$scope.template={};
$scope.template.url = "demo.html";
$scope.$on('$includeContentLoaded', function(event){
$window.alert('content load');
});
}
此外,您可以使用onload
属性设置初始化功能:
html
&lt;div ng-include =" template.url" onload =" arperme()"&gt;&lt;/div&gt; &lt;/div&gt;
控制器
$scope.alertMe=function(){
$window.alert('sending alert on load');
}
包括jQuery和angular.js
和jquery.js
的更改顺序。jQuery必须首先,否则不起作用