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.
Library link here
Create a js file contains the following script and load it in the main file.
(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
module as application dependency:
angular.module('myApp', [
'ngLoadScript'
])
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>
little more to do for loading external js:
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)
}
}
and in partial (activity.html):
<script type="text/javascript-lazy">
loadjscssfile("myjsfile.js", "js");
</script>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…