kittyminky kittyminky - 1 year ago 71
Javascript Question

Angular JS Refactor Controller Dependency Injections

I am wondering if there is a way to abstract out dependencies that are used across multiple Angular Controllers.

For example, if both my

take advantage of
, and
, is there a way to abstract these out into a package of some sort, say
and then inject
into both controllers instead of writing out all of the shared ones?


app.controller('StudentCtrl', ['standardDependencies', function(standardDependencies){


I know this is what services are typically used for I just haven't seen any examples for injecting things like
, only custom functions.

Answer Source

You can't do this for $scope because it might be different for each controller.

Actual singleton-like services, yes, you could technically wrap up into another service:

app.service('standardDependencies', ['$rootScope', ..., function($rootScope, ...) {
  this.$rootScope = $rootScope;

But I don't see any good reason to do so. If StudentCtrl and TeacherCtrl are really that similar, maybe they should both depend on something like PersonService that wraps common functionality.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download