Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>

my activity.html goes like this,

<script type="text/javascript" src="myjsfile.js"></script>

<p>Activity page contents</p>

But the javascript is not getting loaded along with the template.

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.

like image 871
Prasanth K C Avatar asked Apr 27 '26 09:04

Prasanth K C


1 Answers

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>
like image 138
Prasanth K C Avatar answered Apr 28 '26 23:04

Prasanth K C



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!