Created
November 4, 2017 11:44
-
-
Save jberndsen/e32b411396e43c47cb30a042911b4ae9 to your computer and use it in GitHub Desktop.
Run AngularJS initialization logic before main AngularJS app
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// define the module of the bootstrap app | |
var bootstrapModule = angular.module('bootstrapModule', []); | |
// the bootstrap service loads the config and bootstraps the specified app | |
bootstrapModule.factory('bootstrapper', function ($q, $http) { | |
return { | |
bootstrap: function (appName) { | |
var deferred = $q.defer(); | |
// do initial loading here | |
// in our case, this means doing any pre-init async http requests | |
$q.all([$http.get('resources/test-a.json'), $http.get('/test-b.json')]) | |
.then(function (results) { | |
// when they're all loaded, start expanding our actual application | |
var app = angular.module(appName); | |
// declare app factories/constants/etc. that required pre-init here | |
// in our case, using a constant is the least invasive method to retain | |
// current functionality. | |
app.constant('TestAResponse', results[0]); | |
app.constant('TestBResponse', results[1]); | |
// we can now bootstrap the actual application. | |
angular.bootstrap(document, [appName]); | |
deferred.resolve(); | |
}); | |
return deferred.promise; | |
} | |
}; | |
}); | |
// Create a div which is used as the root of the bootstrap app | |
// in the run() function you can now use the bootstrapper service | |
// and shutdown the bootstrapping app after initialization of the actual app | |
var appContainer = document.createElement('div'); | |
bootstrapModule.run(function (bootstrapper) { | |
bootstrapper.bootstrap('app').then(function () { | |
// removing the container will destroy the bootstrap app | |
try { | |
appContainer.remove(); | |
} catch (e) { | |
} | |
}); | |
}); | |
// make sure the DOM is fully loaded before bootstrapping | |
angular.element(document).ready(function () { | |
angular.bootstrap(appContainer, ['bootstrapModule']); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment