我将AngularJs与模板系统一起使用。我想向每个模板添加特定的内联javascript脚本,添加与所选选项卡有关的警报框(主页|列表|设置(
Html渲染:但是添加了ng作用域,当您更改选项卡时没有任何警报。
<script type="text/javascript" class="ng-scope">alert("home")</script>
我在这里提供了一个例子:
http://bit.ly/HWcN1H
或此处
带有警报("template1"(的plunkr示例出现在template1.html中,但呈现为
<script type="text/javascript" class="ng-scope">alert("template1")</script>
我在github 改进了endorama的解决方案
同样的过程。
- 创建angular-loadscript.js(从上面的链接(
-
在您的应用程序中,使用"ngLoadScript"作为资源依赖项。
var app=angular.module('YOUR_app_NAME',['ngResource','ngRoute',…,'ngLoadScript'](;
-
在您的部分使用'text/javascript lazy'作为MIME类型。
一切都应按要求进行:
/*global angular */
(function (ng) {
'use strict';
var app = ng.module('ngLoadScript', []);
app.directive('script', function() {
return {
restrict: 'E',
scope: false,
link: function(scope, elem, attr)
{
if (attr.type==='text/javascript-lazy')
{
var s = document.createElement("script");
s.type = "text/javascript";
var src = elem.attr('src');
if(src!==undefined)
{
s.src = src;
}
else
{
var code = elem.text();
s.text = code;
}
document.head.appendChild(s);
elem.remove();
/*var f = new Function(code);
f();*/
}
}
};
});
}(angular));
有一个通过编码指令的解决方案:
https://gist.github.com/endorama/7369006
var app = ng.module('ngLoadScript', []);
app.directive('script', function() {
return {
restrict: 'E',
scope: false,
link: function(scope, elem, attr) {
if (attr.type=='text/javascript-lazy') {
var code = elem.text();
var f = new Function(code);
f();
}
}
};
});
部分用法:
<script type="text/javascript-lazy" >
alert("lazy loaded");
</script>