如何在我的应用程序中动态加载JS文件

How to load JS file dynamically in my app?

本文关键字:动态 加载 JS 文件 应用程序 我的      更新时间:2023-09-26

>我正在尝试加载一个基于我的JS的外部JS文件。

我已经创建了一个服务来做到这一点

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
});

在我的主控制器中

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

无论如何我可以在我的案例中加载它们吗?多谢!

我对 angular.js 没有太多经验,但除了 eval() 我只看到另一个解决方案需要 jQuery(如果你还没有这样做)。我指的是jQuery.getScript(url,callback)。

这意味着您必须执行以下操作:

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

回调是可选的,它在加载和解释脚本后执行。

这是我使用过的东西,我可以保证会起作用。 另一种解决方案是使用 src= 创建一个脚本标记并将其附加到页面底部。我还没有测试过它,所以我不能 100% 确定它的成功。

像这样:

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){
   });
});