我需要根据应用程序版本在我的 index.html
页面中动态添加脚本。我有一个返回应用程序版本的 Controller ,并尝试使用 angularjs 执行此操作:
var resourceLoader = angular.module('MyTabs', []);
resourceLoader.controller('ResourceLoaderController', ['$scope', '$http', function ($scope, $http) {
$scope.getVersion = function() {
$http.get('/version/get').then(function (response) {
$scope.version = response.data;
var link = document.createElement("link");
link.setAttribute("type", "text/css");
link.setAttribute("rel", "stylesheet");
link.setAttribute("href", '/r/' + $scope.version +'/css/app.css');
document.getElementsByTagName("head")[0].appendChild(link);
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", '/r/' + $scope.version +'/js/app.js');
document.getElementsByTagName("head")[0].appendChild(script);
});
};
$scope.getVersion();
}]);
它可以工作,但是 app.js
中有 Angular Controller ,我在 index.html
中使用的 AuthController
运行时出现错误>, 未定义。
有没有办法在angularjs开始处理网页之前从服务器获取应用程序版本并包含脚本?
最佳答案
AngularJS 的工作原理是,当您包含 .js
文件时,它会创建应用程序并构建所有 Controller /指令/服务字典。
通过在 AngularJS 完成构建之后添加另一个脚本, Controller 将不会添加到应用中。
您需要查找如何动态添加 Controller :Loading an AngularJS controller dynamically
您的另一个选择是在您的 html 引用和构建 AngularJS 依赖项之前获取版本和脚本。这样,当 AngularJS 开始发挥它的魔力时,脚本已经加载。
关于javascript - 在加载 Angular 之前从服务器获取脚本位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34437938/