8

Sorry for the vague title;

I've been restructuring some of my AngularJS code, trying to be more "Angular" about it, and I've noticed this pattern popping up quite a bit:

app.service("someService", function(...) {
    ...
}

app.controller("ControllerForThisSection", function($scope, someService) {
    $scope.someService = someService
}

Basically, the controller is mostly there to give the scope a reference to the service so a view can use it, like

<div ng-if="someService.status">
    ....
</div>

So I have more than a few controllers that do nothing more than depend on certain shared data or services and serve to make references to those services available through the scope.

Is there any disadvantage to using this design? Can I improve my thinking any? Is this the "angular" way to do it?

Thanks for any advice!

cemulate
  • 2,305
  • 1
  • 34
  • 48
  • I'm in a pretty similar situation, though I use directives rather than controllers. I always felt quite confident in going for this pattern, but this is a very interesting question indeed – Aldo Stracquadanio Jun 21 '13 at 11:31
  • Think about a main controller that wraps all the controllers to serve this serivce? – James Kleeh Jun 21 '13 at 12:49

1 Answers1

4

This is the "angular way". Shared data should be placed into services, then injected where needed.

I like to think of my Angular apps mainly in terms of models (which are usually stored in services) and views. The controllers are just the glue that allows us to project/extract the parts of our models that a particular UI view needs.

Also, think of services as returning a model API, not a model object (to quote Josh).

Community
  • 1
  • 1
Mark Rajcok
  • 362,217
  • 114
  • 495
  • 492