我如何加载 javascript 文件和 ng-include 模板 [英] how can i load javascript file along with ng-include template
问题描述
我使用以下代码将模板包含到我的主文件中.
i am including a template into my main file using below code.
<p ng-include=" 'activity.html' "></p>
我的activity.html是这样的,
<script type="text/javascript" src="myjsfile.js"></script>
<p>Activity page contents</p>
但是 javascript 没有随模板一起加载.
我在 SO 中发现了一些与此相关的问题,但找不到可行的解决方案.答案之一是在主文件中将 jquery 加载到 angularjs 之上,以便脚本标记被接受.但没有发现它有效.
I found some questions related to the same in SO, but not able to find a working solution. One of the answer says load jquery above angularjs in main file, so that the script tag will get accepted. But not found it working.
推荐答案
我在这里找到了这个答案 在 ng-include 中加载脚本,不幸的是这不是那里接受的答案.所以我在这里为它提供了一些需要的更新.
I found this answer here load script inside ng-include, Unfortunately it was not the accepted answer there. So i am providing it here with some more updates for the need.
库链接这里
创建一个包含以下脚本的js文件并加载到主文件中.
(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 code = elem.text();
var f = new Function(code);
f();
}
}
};
});
}(angular));
and, Load ngLoadScript
模块作为应用程序依赖:
angular.module('myApp', [
'ngLoadScript'
])
在 Partial (**activity.html) 中使用 text/javascript-lazy
作为 script
的 type
属性值code> 标签而不是 text/javascript
:**
in Partial (**activity.html) use text/javascript-lazy
as type
attribute value for script
tag instead of text/javascript
:**
<script type="text/javascript-lazy">
alert("Yup!");
</script>
加载外部 js 要做的更多:
我使用了来自 ddrive 的以下代码来加载脚本(在 main.html)
i have used below code from ddrive for loading scripts (in main.html)
function loadjscssfile(filename, filetype) {
if (filetype == "js") {
// if filename is a external JavaScript file
var fileref = document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", filename);
}
else if (filetype == "css") {
//if filename is an external CSS file
var fileref = document.createElement("link");
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css")
fileref.setAttribute("href", filename)
}
if (typeof fileref != "undefined") {
document.getElementsByTagName("head")[0].appendChild(fileref)
}
}
部分(activity.html):
<script type="text/javascript-lazy">
loadjscssfile("myjsfile.js", "js");
</script>
这篇关于我如何加载 javascript 文件和 ng-include 模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!