Note that there are some explanatory texts on larger screens.

plurals
  1. POLoading an AngularJS controller dynamically
    text
    copied!<p>I have an existing page into which I need to drop an angular app with controllers that can be loaded dynamically.</p> <p>Here's a snippet which implements my best guess as to how it should be done based on the API and some related questions I've found:</p> <pre><code>// Make module Foo angular.module('Foo', []); // Bootstrap Foo var injector = angular.bootstrap($('body'), ['Foo']); // Make controller Ctrl in module Foo angular.module('Foo').controller('Ctrl', function() { }); // Load an element that uses controller Ctrl var ctrl = $('&lt;div ng-controller="Ctrl"&gt;').appendTo('body'); // compile the new element injector.invoke(function($compile, $rootScope) { // the linker here throws the exception $compile(ctrl)($rootScope); }); </code></pre> <p><a href="http://jsfiddle.net/MzseV/2/">JSFiddle</a>. Note that this is a simplification of the actual chain of events, there are various async calls and user inputs between the lines above.</p> <p>When I try to run the above code, the linker which is returned by $compile throws: <code>Argument 'Ctrl' is not a function, got undefined</code>. If I understood bootstrap correctly, the injector it returns should know about the <code>Foo</code> module, right?</p> <p>If instead I make a new injector using <code>angular.injector(['ng', 'Foo'])</code>, it seems to work but it creates a new <code>$rootScope</code> which is no longer the same scope as the element where the <code>Foo</code> module was bootstrapped.</p> <p>Am I using the right functionality to do this or is there something I've missed? I know this isn't doing it the Angular way, but I need to add new components that use Angular to old pages that don't, and I don't know all the components that might be needed when I bootstrap the module.</p> <p><strong>UPDATE:</strong></p> <p>I've updated the <a href="http://jsfiddle.net/MzseV/3/">fiddle</a> to show that I need to be able to add multiple controllers to the page at undetermined points in time.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload