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

StudentCtrl
and
TeacherCtrl
take advantage of
$scope
,
$rootScope
,
$routeParams
, and
$http
, is there a way to abstract these out into a package of some sort, say
standardDependencies
and then inject
standardDependencies
into both controllers instead of writing out all of the shared ones?

ex.

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
$scope
, 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