AngularJS Load External Config Prior to Bootstrapping
This fiddle is demonstrating loading an external json file with configuration data and then using .config() to configure the AngularJS app prior to manually bootstrapping the application using angular.boostrap.
by keefies
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular-csp.css">
<div id="myApp">
<div ng-cloak ng-controller="MainController">
<h1>{{ name }}</h1>
<p>Service URL: {{ svcUrl }}</p>
<p>API Key: {{ apiKey }}</p>
<p>Children:
<ul>
<li ng-repeat="child in children">{{ child }}</li>
</ul>
</p>
</div>
</div>
JavaScript
// Example module with Config Service and a MainController
angular.module('myApp', [])
.provider('configService', function () {
var options = {};
this.config = function (opt) {
angular.extend(options, opt);
};
this.$get = [function () {
if (!options) {
throw new Error('Config options must be configured');
}
return options;
}];
})
.controller('MainController', ['$scope', 'configService', function ($scope, configService) {
$scope.name = configService.complexData.name;
$scope.children = configService.complexData.children;
$scope.svcUrl = configService.svcUrl;
$scope.apiKey = configService.apiKey;
}]);
// data to simulate data coming from a json file after a 1 second delay.
var data = {
json: JSON.stringify({
svcUrl: 'http://example.com/svc',
apiKey: '5d2334b293af4a8ca19f433d0ebf2f9c',
complexData: {
name: 'Dave Johnson',
children: ['Bobby', 'Sally', 'Steve']
}
}),
delay: 1 // time to delay the JSON response to simulate network latency
};
angular.element(document).ready(function () {
/**
* $.post() is just for JSFiddle example to use their /echo/json/ service.
* To load a static json file you could do a $.get('/path/to/config.json', successCallback)
*/
$.post('/echo/json/', data, function (configData) {
angular.module('myApp').config(['configServiceProvider', function (configServiceProvider) {
configServiceProvider.config(configData);
}]);
angular.bootstrap('#myApp', ['myApp']);
});
});