Adding controller in script tag when using angular

2019-07-19 16:42发布

问题:

When $compile-ing an angular HTML template string I'm trying to put additional controllers and directives inside a <script> tag and use those in the HTML template.

This way I'm essentially trying to implement some sort of plug-in-mechanism, so that I can load external files that augment my app's functionality.

The <script> tag does actually get evaluated, but my problem is, that the HTML template compilation takes place before the evaluation of the JavaScript. So the compiler complains about missing controllers.


Example:

http://plnkr.co/edit/8oZYhRHAjP84ecnl6hG3?p=preview

This example throws an error: Error: Argument 'Controller' is not a function, got undefined

If you delete lines 15-18 (the HTML that references the created conroller) in app.js, you can see in the console that creating a controller this way does actually work.

回答1:

I finally managed to do it based on the solution in Loading an AngularJS controller dynamically. Thx @JoseM, @MaximShoustin and @JussiKosunen for your hints and help.

http://plnkr.co/edit/fzmEZlP6bGBJqTOkfApH?p=preview