I am faced with the challenge of integrating an Angular app with dynamically loaded controllers into an existing webpage.
Below is a code snippet where I have attempted to achieve this based on my understanding of the API and some research:
// Create module Foo
angular.module('Foo', []);
// Bootstrap Foo
var injector = angular.bootstrap($('body'), ['Foo']);
// Define controller Ctrl in module Foo
angular.module('Foo').controller('Ctrl', function() { });
// Insert an element that uses controller Ctrl
var ctrl = $('<div ng-controller="Ctrl">').appendTo('body');
// compile the new element
injector.invoke(function($compile, $rootScope) {
// the linker here throws the exception
$compile(ctrl)($rootScope);
});
JSFiddle. Please note that this is a simplified version of the actual process, as there are various asynchronous calls and user inputs involved between the mentioned steps.
Upon executing the above code, the linker returned by $compile throws an error:
Argument 'Ctrl' is not a function, got undefined
. My understanding was that the injector returned by bootstrap should be aware of the 'Foo' module, right?
If I try creating a new injector using angular.injector(['ng', 'Foo'])
, it seems to work but it introduces a new $rootScope
which is no longer associated with the element where the 'Foo' module was originally bootstrapped.
Am I approaching this correctly or is there something crucial I am overlooking? While I acknowledge that this may not align with Angular's intended methodology, I need to integrate new components utilizing Angular into legacy pages without knowledge of all potential required components at the time of module bootstrapping.
UPDATE:
I have made changes to the fiddle to demonstrate that I require the ability to add multiple controllers to the page at unspecified intervals.