Is it bad practice to assign multiple controllers per route?

2,519 views
Skip to first unread message

Keoki Zee

unread,
Feb 20, 2014, 12:11:08 AM2/20/14
to ang...@googlegroups.com
Is it bad practice in AngularJS to have multiple controllers be responsible for managing a single route? For example, if I have a route set up like this:

$routeProvider.when('/', {
  templateUrl: '../partials/foo.html'
});

and then in foo.html, I have two controllers BarCtrl and SkadooshCrtl like so:

<div ng-controller="BarCtrl"></div>
<div ng-controller="SkadooshCtrl"></div>

I ask because I have an ASP.NET MVC background, where every route is handled by only one controller.

Luke Kende

unread,
Feb 20, 2014, 12:38:41 AM2/20/14
to ang...@googlegroups.com
I don't think it's bad practice.  $scope is setup to be hierarchal and will inherit any parent scopes.  So even if you provided a controller for the template route, it would just be a parent controller to the ones specified within the template. 

Diego Fernandez

unread,
Feb 20, 2014, 5:38:28 AM2/20/14
to ang...@googlegroups.com
I totally agree with Luke Kende.


--
You received this message because you are subscribed to the Google Groups "AngularJS" group.
To unsubscribe from this group and stop receiving emails from it, send an email to angular+u...@googlegroups.com.
To post to this group, send email to ang...@googlegroups.com.
Visit this group at http://groups.google.com/group/angular.
For more options, visit https://groups.google.com/groups/opt_out.

Luke Kende

unread,
Feb 20, 2014, 4:09:08 PM2/20/14
to ang...@googlegroups.com
To expound: 

I actually use routeProvider only for templates and specify my controllers in the root node of the template.  Instead of ng-view, I use ng-include and watch for $routeChangeSuccess to update the template reference as necessary.  What this does is give me control over whether or not I load a new template as I have some routes that point to the same template and don't want them to "reload", but simply have the same controller handle the route parameters differently. (this saves the user a "blink" on the page and prevents it from making the same ajax call twice for the same data that only has a slightly different view).

IMHO, ng-view is just a convenience wrapper for using ng-include with ng-controller mapped to specific routes.  

I could be wrong, but I do not believe there's any special functionality happening when controllers are specified in routeProvider versus in the template.



--
You received this message because you are subscribed to a topic in the Google Groups "AngularJS" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/angular/FO_PsiwNINU/unsubscribe.
To unsubscribe from this group and all its topics, send an email to angular+u...@googlegroups.com.

Keoki Zee

unread,
Feb 21, 2014, 5:00:30 PM2/21/14
to ang...@googlegroups.com
Thanks for the advice guys!
Reply all
Reply to author
Forward
0 new messages