简体   繁体   English

如何从外部调用Angularjs工厂函数

[英]How to call an Angularjs factory function from outside

I have an angular module / factory like this: 我有一个这样的角度模块/工厂:

var app = angular.module('webportal', ['vr.directives.slider', 'angular-flexslider', 'LocalStorageModule', 'multi-select']);

    app.factory('portal', ['uri', function (uri) {
        portal = {};
        portal.getURLParameter = function (name) {
            var hash;
            var vars = [];

            var indexOfQuestion = window.location.href.indexOf('?');

            if (indexOfQuestion != -1) {

                var hashes = window.location.href.slice(indexOfQuestion + 1).split('&');
                for (var i = 0; i < hashes.length; i++) {

                    if (typeof name == 'undefined')
                        vars.push(hashes[i]);

                    else {
                        hash = hashes[i].split('=');
                        if (hash[0] = name)
                            return hash[1];
                    }
                }
            }
        };
        return portal;
    }]);

Now i am trying to call the getURLParameter from outside angular, like this: 现在,我试图从外部角度调用getURLParameter ,如下所示:

angular.injector(['webportal']).get('portal').getURLParameter('blah');

Of course that does not work and fails with: 当然,这行不通,并且失败:

Error: [$injector:modulerr] Failed to instantiate module webportal due to: [$injector:modulerr] Failed to instantiate module vr.directives.slider due to: [$injector:modulerr] Failed to instantiate module ngTouch due to: [$injector:unpr] Unknown provider: ngClickDirectiveProvider http://errors.angularjs.org/1.2.25/ $injector/unpr?p0=ngClickDirectiveProvider minErr/...... 错误:[$ injector:modulerr]由于以下原因而无法实例化模块的Webportal:[$ injector:modulerr]由于以下原因而无法实例化模块vr.directives.slider:由于以下原因,由于以下原因而无法实例化模块ngTouch:注射器:unpr]未知提供者:ngClickDirectiveProvider http://errors.angularjs.org/1.2.25/ $ injector / unpr?p0 = ngClickDirectiveProvider minErr / ......

So can anyone tell me what is the proper way to call this? 那么有人可以告诉我什么是正确的称呼方式吗?

戳了一下之后发现了答案:

angular.element(document.body).injector().get('portal').getURLParameter('blaha')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM