0

I would to dynamically load controller in my partial file so my code is better organized. Through my research, I found that if I want to load controller from partial using the script tag, I need to include JQuery.

However, these approach seem to only work if my controller is declared in the global scope, i.e.

function MainCtrl($scope) {}

If I switch to using module in my controller.js

angular.module ("myApp").controller ("MainCtrl", function ($scope) {});

this no longer work with the error message "Argument 'MainCtrl' is not a function, got undefined"

Below is a plunker to demonstrate this.

http://plnkr.co/wNv3UD

How could I make this work?

Note I did not include controller.js in index.html intentionally. I want to load controller from the partial.html, since it would only be used there.

Edit I was able to achieve what I wanted to to after reading this question: AngularJS Dynamic loading a controller

This seem to be a straightforward approach to support lazy loading. Hopefully the $controllerProvider.register method could be exposed through angular.module.controller in future versions to support lazy loading.

Community
  • 1
  • 1
ltfishie
  • 2,917
  • 6
  • 41
  • 68
  • you forgot to include your `` in the `` and since you declared `var app` to be your module use it `app.controller()` dont include it in the partial if you want better usage look into loaders such as requirejs – David Chase Aug 24 '13 at 22:07
  • I include the script from partial.html, which is the point of my question. I know this works if move the script tag to index.html – ltfishie Aug 24 '13 at 22:09
  • Again I would not recommend that approach you should use a script loader such as requirejs if you want to organize your dependencies or files – David Chase Aug 24 '13 at 23:14
  • Correct me if I am wrong, but I think even with require.js, you could not achieve lazy loading without exposing $controllerProvider with Angular. So while require.js would certainly help organize dependencies better, it will not solve this issue directly. – ltfishie Aug 27 '13 at 02:40

2 Answers2

2

You may want to take a look at [RequireJS][1] it provides a good and easy way for you to load your .js files on the run.

for the dynamic controller loading part: you should write a provider (a service) which exposes some methods to register your controllers wile the angular app is running (take a look at $controllerProvider in angular docs)

i suggest you take a look at this post as it mentions how to fully customize your application regarding the script loading and controller registeration and stuff like that.

Kia Panahi Rad
  • 1,235
  • 2
  • 11
  • 22
0

You can achieve this using custom directive and in directive you can load script using jquery getscript or jQuery ajax call, directive will fire when you load the partial

JQuery Guru
  • 6,943
  • 1
  • 33
  • 40