2

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.

1 Answer 1

12

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.