George Tsopanoglou George Tsopanoglou - 1 month ago 11
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) {
scope.foo = $rootScope.foo;
}
});

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?

Answer

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) {
          sameInitService.init(locals.$scope);
          return $delegate(constructor, locals, true);
        }
      }

    ]);
  }])

See jsfiddle here.