Here is an illustration showcasing the loading of a configuration file prior to bootstrapping the application.
The initial call to bootstrap is made to access angular services such as $http and $location (you also have the option to inject your own module at this stage in order to utilize custom services).
Once the configuration file is loaded, angular.bootstrap is invoked for the main application, with the loaded configuration being defined as a constant on a makeshift module(rsacAppBootstrap) that gets injected.
There are at least two benefits compared to using a promise set from a run block:
- Less repetition of promises for all elements relying on configuration
- Possibility to selectively load dependencies based on the environment using RequireJS
Customized bootstrap script:
angular.bootstrap().invoke(function ($http, $location) {
var env = $location.search()._env || null;
if (env === true) {
env = null;
}
var configUri = 'config/env.json';
if (env) {
configUri = configUri.replace('json', env + '.json');
}
var rsacAppBootstrap = angular.module('rsacAppBootstrap', [])
.run(function ($rootScope, $location, $window) {
var env = $location.search()._env;
$rootScope.$on('$locationChangeSuccess', function () {
var newEnv = $location.search()._env;
if (env !== newEnv) {
$window.location.reload();
}
})
});
function bootstrap(config) {
rsacAppBootstrap.constant('rsacConfig', config || {});
angular.element(document).ready(function () {
var modules = ['rsacApp', 'rsacAppBootstrap'];
if (config.modules){
config.modules.forEach(function(v){
modules.push(v);
})
}
angular.bootstrap(document, modules);
});
}
$http.get(configUri)
.success(function (config) {
config._env = env;
if (config.require) {
require(config.require, function(){
bootstrap(config);
});
} else {
bootstrap(config);
}
})
.error(function () {
bootstrap();
});
});
Sample configuration file:
{
"_meta": [
"Development environment settings"
],
"require":[
"//code.angularjs.org/1.2.3/angular-mocks.js",
"components/rsacMock/js/rsacMock.js"
],
"modules":[
"ngMockE2E",
"rsacMock"
],
"resources": { ... }
}