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

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

问题描述

我仍然在Angularjs一个初次登台。
我想在我的控制器动态地将服务的依赖(即我创建的)。

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

但是,当我code具有相关性的服务,我得到这个错误:

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

错误:未知提供商:$ windowProvider< - $窗LT; - 的base64

这是控制器的code。

This is the code of the controller.

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

这code工作:

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

    };

});

这code不工作:

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

错误:未知提供商:$ routeProvider从mainModule

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

JS小提琴

同一模块: 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/

Different module without dependencies : http://jsfiddle.net/yrezgui/YedT2/5/

推荐答案

不要叫angular.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;
};

又见<一个href=\"http://stackoverflow.com/questions/14415845/angularjs-dynamically-inject-scope-or-controller\">AngularJS动态范围注入或控制器

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

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