动态地向控制器注入服务

Dynamically inject service to a controller

而不是像这样在控制器中指定所有服务:

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);

可以使用 $inject 吗? 我正在使用 $attrs 从 html 获取规范,我应该使用哪个服务。

您可以 $injector 依赖于您的控制器,然后 $injector.get 获取服务对象。

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

基本上 $injector.get 方法将搜索您在 angular context & return 中提供的任何服务名称,如果找到的话 object

代码

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()');
}

是的,你可以注入$injector,然后像这样使用它:

var brancesService = $injector.get('brancesService');