Reputation: 323
I come from the Rails world, where a controller is responsible to do business logic but a single controller can render several views, depending on the action that is supposed to do.
However, and after doing some research on AngularJS, I have the feeling that a controller will just have one responsability (associated with a single view). So, for example, if we have an application that lists restaurants, we would have the following:
@restauranteur.config(['$routeProvider', ($routeProvider) ->
$routeProvider.
when('/restaurants', {
templateUrl: '../templates/restaurants/index.html',
controller: 'RestaurantIndexCtrl'
}).
when('/restaurants/:id', {
templateUrl: '../templates/restaurants/show.html',
controller: 'RestaurantShowCtrl'
}).
otherwise({
templateUrl: '../templates/home.html',
controller: 'HomeCtrl'
})
])
One controller would be used for the 'index' and another for the 'show'. Is this the correct approach/suggested approach in Angular?
Upvotes: 3
Views: 1405
Reputation: 2198
As you can read in official documentation, in general, a Controller shouldn't try to do too much. It should contain only the business logic needed for a single view.
The most common way to keep Controllers slim is by encapsulating work that doesn't belong to controllers into services and then using these services in Controllers via dependency injection.
In Angular, a Controller is a JavaScript constructor function that is used to augment the Angular Scope.
When a Controller is attached to the DOM via the ng-controller directive, Angular will instantiate a new Controller object, using the specified Controller's constructor function. A new child scope will be available as an injectable parameter to the Controller's constructor function as $scope.
Use controllers to:
Do not use controllers to:
To answer shortly your question - yes, this is correct approach
Upvotes: 6