0

Suppose that I have a huge web application (that uses AngularJS) with a lot of controllers. Is there a way to inject $log service in every controller? To be more clear, I want to write something like this:

.config(function($log) {
    allMyControllers.inject($log);
})

instead of

.controller('Controller1', function($log) {...})
.controller('Controller2', function($log) {...})
.controller('Controller3', function($log) {...})
.controller('Controller4', function($log) {...})
not a Programmer
  • 175
  • 1
  • 14
  • Possible duplicate of [What's the recommended way to extend AngularJS controllers?](https://stackoverflow.com/questions/16539999/whats-the-recommended-way-to-extend-angularjs-controllers) – Lex Sep 10 '18 at 13:54
  • https://stackoverflow.com/questions/32266653/inject-service-in-all-controllers – Jonathan Anctil Sep 10 '18 at 20:29

1 Answers1

1

Possible thing that you can do is, create a controller that has all needed dependencies and make it as base controller and other controllers can extend it using angular extend api.

some clear example code which I came accross :

.controller('baseController', function(someService) {
this.someService = someService;
})

.controller('extendedController', function($scope, $controller) {
  angular.extend(this, $controller('baseController', { $scope: $scope }));

  this.alert = this.someService.alert;

})

.service('someService', function() {

  this.alert = function() {
    window.alert('alert some service');
  };
});

Working solution of above code can be found here.

Naveen Kumar G C
  • 1,332
  • 1
  • 10
  • 12