如何在控制器中动态注入依赖 [英] How to $inject dynamically dependence in a controller

查看:23
本文介绍了如何在控制器中动态注入依赖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仍然是 Angularjs 的新手.我想在我的控制器中动态注入一个服务(我创建的)的依赖项.

I'm still a debutant on Angularjs. I want to inject dynamically a dependency of a service (that I created) in my controller.

但是当我编写具有依赖项的服务时,出现此错误:

But when I code a service with dependencies, I got this error :

错误:未知提供者:$windowProvider <- $window <- base64

这是控制器的代码.

var base64 = angular.injector(['servicesModule']).get('base64');
console.log("base64", base64.encode("my text will be encoded"));

此代码有效:

var servicesModule = angular.module('servicesModule', []);
servicesModule.factory('base64', function() {
    return {

        name: 'base64',
        readonly: false,

        encode: function(input) {
            return window.btoa(input);
        },

        decode: function(input) {
            return window.atob(input);
        }

    };

});

此代码不起作用:

var extModule = angular.module('ext', []);
extModule.factory('base64', ['$window', function($window) {
    return {

        name: 'base64',
        readonly: false,

        encode: function(input) {
            return $window.btoa(input);
        },

        decode: function(input) {
            return $window.atob(input);
        }

    };

}]);

另一个问题是当服务与控制器在同一个模块中时.如果模块有依赖项,我将无法工作(我的模块配置中有 $routeProvider 依赖项):

Another problem is when the service is in the same module as the controller. If the module has dependencies, I doesn't work (I have $routeProvider dependence in my module config) :

错误:未知提供者:来自 mainModule 的 $routeProvider

var mainModule = angular.module('main', [],
    function($routeProvider, $locationProvider) {
        //Some routing code
    }
);

JS 小提琴

具有依赖项的相同模块(控制器 + 服务):http://jsfiddle.net/yrezgui/YedT2/

Same module with dependencies(controller + service) : http://jsfiddle.net/yrezgui/YedT2/

具有依赖项的不同模块:http://jsfiddle.net/yrezgui/YedT2/4/

Different module with dependencies : http://jsfiddle.net/yrezgui/YedT2/4/

没有依赖的不同模块:http://jsfiddle.net/yrezgui/YedT2/5/

推荐答案

不要调用 angular.injector() —— 这会创建一个新的注入器.相反,将已经创建的 $injector 注入您的控制器并使用它:

Don't call angular.injector() -- this creates a new injector. Instead, inject the already-created $injector into your controller and use it:

所以代替:

var algoController = function($scope) {
    $scope.base64 = angular.injector(['main']).get('base64');
};

这样做:

var algoController = function($scope, $injector) {
    $scope.base64 = $injector.get('base64');
};

但大多数时候你应该直接注入你的服务,而不是像这样动态注入:

But most of the time you should inject your service directly, rather than dynamically, like so:

var algoController = function($scope, base64) {
    $scope.base64 = base64;
};

另见 AngularJS 动态注入作用域或控制器

这篇关于如何在控制器中动态注入依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆