问题
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.
回答1:
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
回答2:
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.
来源:https://stackoverflow.com/questions/23696807/specifying-angularjs-controller-benefits-using-ngcontroller-vs-routeprovider