danday74
danday74

Reputation: 56956

Is automatic dependency injection available in AngularJS?

I want to automatically dependency inject an Angular built-in service into all services within an Angular module / app.

The service I want to inject is ... $exceptionHandler

I do not want $exceptionHandler to be global ... e.g. I do not want to do ...

window.$exceptionHandler = $exceptionHandler

But I also do not want to dependency inject $exceptionHandler into every service manually using ...

angular.module('myApp').factory('myService', ['$exceptionHandler', function ($exceptionHandler) {

Is it possible to automatically inject an Angular built-in service into all services within an Angular module / app ?

Many thanks

Upvotes: 4

Views: 1452

Answers (1)

It can be made more convenient through nested modules. In the root (or global) module inject $exceptionHandler and all the other modules you create or want to use. All sub modules of the root module will have $exceptionHandler injected without further ado. You still have to name the $exceptionHandler in your controller and factory function definitions, though, so it is not possible to completely get rid of injection artefacts.

Example:

app.js

angular.module('app', ['ionic', '$exceptionHandler', 'ngCordova','app.home',
'app.impressum'])

.run(function ($ionicPlatform, $state) {
   ..
})
.config(function ($stateProvider, $urlRouterProvider, $provide, $exceptionHandler, $ionicConfigProvider, $compileProvider) {

    $stateProvider
        .state('app', {
            ...
        })
    }
);

Now the app.home-Module:

home.js

angular.module('app.home', ['app.home.controller', 'app.home.factory']);

home/controller.js

angular.module('app.home.controller', [])
  .controller('homeController', function ($scope, $exceptionHandler) {
    ...
  });

app.home.factory and the three modules for app.impressum are quite similar, so I leave that to you.

As you can see you still have to put $exceptionHandler into the function parameters of your controller, but no injection is required on the module itself, because it inherits all injections from it's parent modules app.home and app.

By using a hierarchy of modules in an AngularJS app injections can be made where due... more globally for the whole app, for module groups or only on single modules. Plus we get a very clean structure for the App's sections.

Upvotes: 3

Related Questions