vvohra87
vvohra87

Reputation: 5674

Angularjs - injecting dependencies into multiple controllers

I'm still quite new to angular, and have been building a simple CRM application. For a single resource (restful API resource) I have 3-4 routes and controllers defined in my angular application. Now, there are a set of services and modules that I repeatedly have to inject into each controller. I understand that each controller will have it's own instance of scope and shared instance of factory/services but is there a way to centrally define dependencies for multiple controllers?

In the example below, $modal, growl, configuration, $scope are injected into all 3 controllers, I'd like to define that only once.

Listings Controller

myApp.controller('VenueListCtrl', ['$scope', '$http', 'configuration', '$modal', 'growl',
  function ($scope, $http, configuration, $modal, growl) {
  }
]);

Create/New Controller

myApp.controller('VenueCreateCtrl', ['$scope', '$http', '$location', 'configuration',
  function ($scope, $http, $location, configuration) {
  }
]);

Details Controller

myApp.controller('VenueDetailCtrl', ['$scope', '$routeParams', '$http', '$modal', 'configuration',
  function ($scope, $routeParams, $http, $modal, configuration) {
  }
]);

Upvotes: 2

Views: 1381

Answers (1)

Rasalom
Rasalom

Reputation: 3111

Best you can do is: use not-anonymous function declaration of controllers:

var depsToInject = ['$scope', 'growl', 'configuration', '$modal'];

myApp.controller('Ctrl1' , Ctrl1);

Ctrl1.$inject = depsToInject ;

function Ctrl1($scope, growl, configuration, $modal) {
    // ...
}

myApp.controller('Ctrl2' , Ctrl2);

Ctrl2.$inject = depsToInject ;

function Ctrl1($scope, growl, configuration, $modal) {
    // ...
}

etc. But that does not fully unify declaration and I don't think there is a better way. However you can try from the other side and wrap your dependencies with another dependency, but I don't like this way either.

Upvotes: 1

Related Questions