Search code examples
javascriptangularjsangularjs-serviceangularjs-injector

Dynamically inject service to a controller


Instead of specifying all the services in a controller like:

mainApp.controller('MultiController', ['$scope', '$attrs', '$branchesService', '$repositoriesService', function ($scope, $attrs, $branchesService, $repositoriesService) {
console.log('multiController instantiated');
var vm = this;

// private idu funkcija definition bez scope
vm.init = function(mod) {
    vm.mod = mod;
    if (mod == "branch") {
        console.log('MultiController branchesService');
        vm.service = $branchesService;
    } else {
        console.log('MultiController repoService');
        vm.service = $repositoriesService;
    }

    vm.items = [];
    vm.selectedItem = null;
    vm.error = 'no Error at the moment...';

    loadRemoteData();
    console.log('multiController.init()');
}
vm.init($attrs.mod);

Is it possible to use $inject ? I am using $attrs to get a spec from html, which service should I use.


Solution

  • You could $injector dependency inside your controller and then do $injector.get to get service object.

    $injector is used to retrieve object instances as defined by provider, instantiate types, invoke methods, and load modules.

    Basically $injector.get method will search for whichever service name you provide inside angular context & return the object if its found.

    Code

    vm.init = function(mod) {
        vm.mod = mod;
        if (mod == "branch") {
            console.log('MultiController branchesService');
            vm.service = $injector.get('branchesService'); //you will have service instance here
        } else {
            console.log('MultiController repoService');
            vm.service = $injector.get('repositoriesService'); //you will have service instance here
        }
    
        vm.items = [];
        vm.selectedItem = null;
        vm.error = 'no Error at the moment...';
    
        loadRemoteData();
        console.log('multiController.init()');
    }