George Tsopanoglou George Tsopanoglou - 3 months ago 32
AngularJS Question

Run same piece of code when injecting an angular service

I want to run the same line of code to each function a specific service is injected. For instance:

app.service('sameInitService', function ($rootScope) {
this.init = function (scope) { = $;

app.controller('oneController', function ($scope, sameInitService) {
sameInitService.init($scope); // <- This line of code

app.controller('twoController', function ($scope, sameInitService) {
sameInitService.init($scope); // <- Is the same

Is there an angular-ish way to avoid having to write the same line of code when this service is injected?


It can be done by decorating the $controller service but in this case all your controllers will be initialized this way.

angular.module('App', [])
  .config(['$provide', function($provide) {

    $provide.decorator('$controller', [
      '$delegate', 'sameInitService',
      function controllerDecorator($delegate, sameInitService) {

        return function(constructor, locals) {
          return $delegate(constructor, locals, true);


See jsfiddle here.