1

So I'm an Angular noob trying to introduce AngularJS to an already existent RoR environment.

Since it's a relatively heavy and robust web app, I thought the best way to go about it would be to write a controller for each section in its' own file (coffee, for the record), and load it with the view through $routeProvider, registering the controller dynamically by doing something like this (omitting irrelevant parts):

app.config [
   "$routeProvider", "$controllerProvider", 
   ($routeProvider, $controllerProvider) ->
      app.registerCtrl = $controllerProvider.register
      $routeProvider
         .when("url1",
           templateUrl: "url1.html.haml"
           controller: "url1Ctrl"
         )
         .when("url2"
           templateUrl: "url2.html.haml"
           controller: "url2Ctrl"
         )
         .otherwise redirectTo: "/homepage"

I load the main js file (and in it the above snippet) in the layout file, and each designated controller file in the appropriate view (that is dynamic, obviously). In each of them, I try to load the relevant controller using:

@url1Ctrl = app.registerCtrl 'url1Ctrl', [
   '$scope', ....., 
   ( $scope, ....) ->
     # some logic

Problem is, I get an error saying "Uncaught TypeError: undefined is not a function". I thought I was doing something wrong with the provider function but it seems I'm being a lawful citizen there. Also read a bunch of similar questions on SO:

How to separate Controller file in angularjs (basically using ".controller" instead of registering it? Didn't work for me)

Separating Controllers in AngularJS (same idea)

How to create separate AngularJS controller files? (same, but the controller files are always loaded, not lazy-loaded dynamically...)

Loading an AngularJS controller dynamically (seems like an over-complication?)

AngularJS Controller Not Registering (tried it, not the same issue i'm having, it seems)

Would love some input on what part of Angular I'm misinterpreting here.

3
  • Angular doesn't support loading controllers (or other components) dynamically. So the solution that you regard as 'over-complication' is the one for you. Commented Jan 22, 2015 at 15:49
  • @zeroflagL Really!? Doesn't that mean one would have to make ALL the API calls needed for ALL sections of the app before the initial state is loaded!? If not - how do i trigger these calls upon changing tabs (and controllers, for that matter) otherwise? Commented Jan 25, 2015 at 9:39
  • Basically, yes. What you try to do with the $controllerProvider should work, but it's kind of a hack, imho. Uncaught TypeError: undefined is not a function is no Angular error, though. If you are sure that the error is thrown by app.registerCtrl then app probably isn't a global variable. Commented Jan 25, 2015 at 11:11

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.