您应该使用任何依赖项/模块加载器,例如 requirejs,以使您的依赖项加载在应用程序中更有条理。
要在 DOM 中动态加载脚本,可以使用这样的函数 -
var loadScript = function (url, callback) {
var script = document.createElement("script");
script.type = "text/javascript";
if (script.readyState) { //IE
script.onreadystatechange = function () {
if (script.readyState == "loaded" || script.readyState == "complete") {
script.onreadystatechange = null;
console.log(url + ' loaded successfully.');
if ($.isFunction(callback)) {
callback();
}
}
};
} else { //Others
script.onload = function () {
console.log(url + ' loaded successfully.');
if ($.isFunction(callback)) {
callback();
}
};
}
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}
此函数应驻留在预先加载的任何脚本中(即 config.js)。如果不需要,可以避免使用第二个参数。它只是为您提供了一种在脚本加载后如果您需要做某事的便利。
这是使用您的 myApp 对脚本加载功能的演示调用 -
var myApp = angular.module('myApp', ['ionic','ionic-datepicker','ui.router','toaster','ngAnimate']);
myApp.run(function(){
config.loadScript('yourScriptPath', null);
})
.config(function($stateProvider, $urlRouterProvider) {
//==========================================================================//
// Build the pages up for the application with their respective controllers //
//==========================================================================//
$stateProvider
.state('login', {
cache : false,
url : '/',
controller : "LoginController",
templateUrl : 'login.html'
})
.state('page1', {
cache : false,
url : '/page1',
controller : "page1controller",
templateUrl : 'page1.html'
})
.state('page2', {
cache : false,
url : '/page2',
controller : "page2controller",
templateUrl : 'page2.html'
})
.state('page3', {
cache : false,
url : '/page3',
controller : "page3controller",
templateUrl : 'page3.html'
});
$urlRouterProvider.otherwise('/');
});
谢谢