Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

specifying AngularJS controller: benefits using ngController vs. $routeProvider

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.

like image 817
nshew13 Avatar asked May 16 '14 13:05

nshew13


People also ask

What is the $routeProvider in AngularJS used for?

The $routeProvider is creates the $route service. By configuring the $routeProvider before the $route service we can set routes in HTML templates which will be displayed. The $routeProvider is configured with the help of calls to the when() and otherwise() functions.

Which directive do you use with routing to display a template?

The role of the ngView directive is to include the view template for the current route into the layout template.

Why routing is not working in AngularJS?

The problem is the default hash-prefix used for $location hash-bang URLs is ('! ') that's why there are additional unwanted characters in your URL. If you actually want to have no hash-prefix and make your example work then you can remove default hash-prefix (the '!'

What is dollar route provider?

A - $routeProvider is the key service which set the configuration of urls. B - $routeProvider maps Urls with the corresponding html page or ng-template. C - $routeProvider attaches a controller with the view.


1 Answers

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.

like image 169
drew_w Avatar answered Dec 19 '22 23:12

drew_w