0

I often need more than one controller in a single route and I'd like to know if I can use this kind of syntax:

angular.module('app', ['ngRoute'])

.config(['$routeProvider', function($routeProvider){
  $routeProvider.when('/', {
     template : 'index.html',
     controller : ['Ctrl1', 'Ctrl2']
  });
}]);

index controller folder

angular.module('app')

.controller('Ctrl1', function(){

})

.controller('Ctrl2', function(){

});

Controllers can become very large.
The purpose is to load them only when needed.

gr3g
  • 2,866
  • 5
  • 28
  • 52
  • 1
    You could divide up the view into separate views and attach a controller to each child. [ui-router](http://angular-ui.github.io/ui-router/site/#/api/ui.router) can do this for you. – skubski Jul 02 '15 at 10:21
  • I'd like to use only pure angularJS, but from what I've heard ui-router seems to be better – gr3g Jul 02 '15 at 11:01

1 Answers1

0

You don't need to define controllers on the route, you can define them on your HTML:

JS:

angular.module('app', ['ngRoute'])
.config(['$routeProvider', function($routeProvider){
  $routeProvider.when('/', {
     template : 'index.html',
  });
}]);

angular.module('app')

.controller('Ctrl1', function(){

})

.controller('Ctrl2', function(){

});

HTML:

<div ng-controller="Ctrl1"></div>
<div ng-controller="Ctrl2"></div>
michelem
  • 14,430
  • 5
  • 50
  • 66
  • But that becomes a mess if you have a big application isn't it? – gr3g Jul 02 '15 at 10:15
  • How do you use them if you don't define them on the HTML? Using a controller in a route has different purpose. – michelem Jul 02 '15 at 10:17
  • defining them in the route is just an options to not display it in your template with `ng-controller="Ctrl1"` – gr3g Jul 02 '15 at 10:20
  • Referencing a controller in a route does not have a different purpose. – skubski Jul 02 '15 at 10:21
  • @greg so that doesn't make sense, how can you handle 2 controllers in the same template without defining them in a specific element? – michelem Jul 02 '15 at 10:23
  • It doesn't make sense to have one view and two viewmodels. It does however make sense to keep only file that defines your views and their viewmodels (read controllers). – skubski Jul 02 '15 at 10:28
  • Seems like (from the angular up and running book), the real purpose (in advantage of an option) is to pass paramaters when you resolve your route. When you resolve and inject that in your controller that controller HAS to be defined in your route – gr3g Jul 02 '15 at 10:54
  • @Michelem Now, I'm passing one controller in the route and the others into directives – gr3g Jul 02 '15 at 10:56
  • Does any of you know a medium size opensource project to see how to get things organized? – gr3g Jul 02 '15 at 10:59
  • 1
    Check this full-stack very well organised: http://meanjs.org/ – michelem Jul 02 '15 at 11:00