.config, .run, AppCtrl - where to put routes?
Asked Answered
S

2

28

I wanted to find out the difference between the .config and .run functions in AngularJS. I was using my .config for setting up routes, but I did have some $on's for watching route change start and success events.

I then moved some of this code to .run as I was having some dependency injection problems in .config.

I finally moved some of this to a CommonAppController which I have set on my <body>.

I also had 2 .config's and it seemed to be running ok, but surely this isn't right?

Can anyone give a little insight on which method to use?

Shick answered 8/8, 2013 at 10:23 Comment(1)
Can you please share how did you manage in common controller? I tried to use root controller and redirect to login page if user is not authenticated. The issue was that the child controller was still being invoked. Any help is highly appreciated.Sundew
A
78

Configuration blocks and run blocks get executed at different points in the application bootstrap, and have different injection locals at their disposal. Here's a summary of what you can find in the AngularJS documentation.

Configuration blocks (registered with module.config()) get executed during provider registration, and can only be injected providers and constants (see module.provider() and module.constant()). This is typically where you would configure application-wide stuff, such as the $routeProvider. Stuff that needs to be configured before the services are created.

Run blocks (registered with module.run()) get executed after the injector has all the providers. Now, all instances and constants can be injected. This is typically where you would configure services, $rootScope, events and so on.

You can have multiple of either, and they are executed in the order they were registered to the module. Some people prefer to register a configuration block before every group of controllers to register the routes to these controller, for example.

Admiration answered 8/8, 2013 at 11:25 Comment(1)
Thanks Steve, great explanation ! So with regards to watching events - global events, like changelocationstart etc.... Run sounds like a great place but I could actually do this in a App Controllers - any reason to use one over the other ? ThanksShick
D
-1

The .config block is executed during the provider registration and configuration phase. It' a module level block.

The.run block is executed after the config block. It's used to inject services and constants.

Doerr answered 14/9, 2017 at 3:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.