I would like to hear your thoughts, idea's or feedback on the following code.
Ive added to code to github.
https://github.com/redbullzuiper/angularjs-dynamic-controllers
Usually when you attach a controller to a DOM element using ng-controller="myController"
, you need to include the controller somewhere in your page; for instance:
<script src="src/application/controllers/my-controller.js"></script>
However, when including the script I wrote in the head
, it will traverse across the DOM and search for all ng-controller
attributes.
It will then automatically append the correct controller into the head
of the page. After it's done including all the controllers, it will manually bootstrap the application using:
angular.bootstrap(document, ['module_name']);
This way all controllers are getting loaded dynamically, without the need of including all controllers in your head
. But they will instead only get loaded when called.
Can't create a demo using a fiddle, but a working demo can be found here
The code:
window.onload = function()
{
var promises = [];
var ngApp = document.querySelectorAll('[ng-app]')[0];
var ngControllers = document.querySelectorAll('[ng-controller]');
// Throw warning if angular is not found
if(typeof angular == 'undefined')
{
console.warn("simplify error: Angular not found, operation canceled.");
return;
}
// Throw warning if ng-app directive exists. Script will bootstrap the application manually
if(ngApp)
{
console.warn("Please remove the ng-app directive. `Simplify` will bootstrap the application manually.");
console.warn("This will also most likely fix the 'Uncaught Error: [$injector:modulerr]' error.");
}
// Append the scripts
for(var i = 0;i < ngControllers.length;i++)
{
var promise = new Promise(function(resolve, reject) {
var src = 'src/application/controllers/'+ ngControllers[i].getAttribute('ng-controller') + '.controller.js';
var script = document.createElement('script');
script.setAttribute('src', src);
document.head.appendChild(script);
script.addEventListener('load', function() {
resolve(script);
});
});
// Push promises to array to resolve them all together later on
promises.push(promise);
}
// Resolve all promises then bootstrap the app
// Without the use of promises, the bootstrap will start before all scripts are included
// This results into an erro
Promise.all(promises).then(function() {
angular.bootstrap(document, ['app']);
});
}