Search code examples
javascriptdesign-patternsangularjsangularjs-scopeangularjs-service

AngularJS philosophy - controllers as "windows" to services


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!


Solution

  • 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).