16

There are two ways (AFAIK) to associate a controller with a view template/partial: the route specified in $routeProvider and the ngController directive. Especially (but not exclusively) for simple routing, is there any benefit/efficiency of one over the other?

My project currently uses the $routeProvider approach, but I've been given the task of nesting views. This seems simple enough with ngInclude, as long as the partial specifies its ngController.

2 Answers 2

14

This question really comes down to design and as such it is a bit opinion based. That in mind, the best guidance I know is:

  • $routeProvider - Allows you to specify a single controller for a template. Since this is part of the routing it makes it easy to find the controller that goes with the page. I use this to store and load overall page logic rather than element specific logic.

    This is also important because it means you can load the exact same template for two different routes but the behavior and data could be different because the controller can be changed. This is not something that is easy to do with the ngController option.

  • ngController - This scopes the controller to a specific element on the page/template. That can make the code easier to read when you need multiple controllers on a single page and it allows the controller to be more specifically scoped.

So it really comes down to scope and intent. Hopefully these rules will help when deciding which to use.

5

If you think of a view including all scripts as a self-contained package, developed by a single person or team, then ngController is the way to go, imho.

$routeProvider on the other hand provides you with advanced features like injection of values via the resolve property of the route. That way you can have your AJAX loaded data directly injected into your controller, e.g., instead of the controller having it to get itself. Or have the route change to wait for that data etc.

Btw: If you need routing and nested views you can take a look at angular ui-router

1
  • Thanks a lot for this answer! I'm currently using $stateProvider instead of $routeProvider, does the same thing applies here?
    – 0x1ad2
    Dec 8, 2015 at 9:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.