0

I am trying to load an external JS file based dynamically in my JS.

I have created a service to do it

angular.module('myApp').service('testService', function($http) {
        var prefix;
        //codes to determine what prefix is.
        // It could be http://partnerapp.com/test or http://linkapp.com/test/libs/...etc
        var url = prefix + '/js/test.js';
        return $http({
                method: 'GET',
                url: url
        }); //load JS file
});

in my main controller

angular.module('myApp').controller('myController', function($scope, testService){
    //I am not sure how to load those js here. 
})

Is there anyway I can load them in my case? Thanks a lot!

2 Answers 2

1

I don't have much experience with angular.js, but except eval() I see only one other solution an it requires jQuery (if you haven't done this already). I'm referring to jQuery.getScript(url, callback).

This means you'll have to do something like this:

var url = prefix + '/js/test.js';
$.getScript(url); //load JS file and execute script

Callback is optional and it's executed after the script is loaded and interpreted.

This is something I've used and I can guarantee will work. another solution is to create a script tag with src= and append it to the bottom of the page. I haven't tested it yet so i'm not 100% sure of its success.

Sign up to request clarification or add additional context in comments.

2 Comments

I am getting 414 request-url too large error in the console. Anyway to fix it? +1
Can you do a "console.log(url, url.length)" and see what are the values? Or in the network tab of the chrome inspector, can you check the URL? What programming language did you use for the server and what do you host it in?
0

Something like :

angular.module('myApp').controller('myController', function($scope, testService){
    testService.then(function(data){
        //you can console.log(data) and after maybe eval it ?
        eval(data);//eval can be harmfull
    }, function(error){

   });
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.