全局函数中的Angular.js依赖注入

时间:2014-10-29 11:00:57

标签: javascript angularjs dependency-injection cordova-3

我正在用angular.js编写一个cordova应用程序。当我使用PushPlugin向用户发送推送通知时。我已经注册了这样的用户手机:

var pushNotification = window.plugins.pushNotification;
    pushNotification.register(successHandler, errorHandler, { "senderID": [gmc_project_number], "ecb": "app.onNotificationGCM" });

我传递的最后一个参数是app.onNotificationGCM这是我收到通知时调用的函数。

这是该功能的实现:

 app.onNotificationGCM = function (e) {
    switch (e.event) {
        case 'registered':
            if (e.regid.length > 0) {
                console.log("Regid " + e.regid);
                alert('registration id = ' + e.regid);
            }
            break;

        case 'message':
            // this is the actual push notification. its format depends on the data model from the push server
            alert('message = ' + e.message + ' msgcnt = ' + e.msgcnt);
            break;

        case 'error':
            alert('GCM error = ' + e.msg);
            break;

        default:
            alert('An unknown GCM event has occurred');
            break;
    }
};

我必须将它添加到全局变量(在本例中为angular.module)中,以便在返回响应时可以访问它。

这是我从https://github.com/phonegap-build/PushPlugin/issues/309

得到的解释
  

因为Android JAVA代码调用了一个函数(我在中看到它)   LogCat)调用sendJavascript()这个函数包含一个字符串   包含在函数中调用的onNotificationGCM(Json)函数   如果您在“onDeviceReady”中加载该函数,那么它将是   只有当设备准备就绪并且不总是那样时才可用   应该是(登记需要几秒钟才能回来)

现在它的工作正常。问题是我想调用工厂并在onNotificationGCM内从它进行http调用。目前我不知道如何注射工厂。 我尝试将onNotificationGCM函数分配给$rootScope,但在回复中无法访问。

有没有办法在这个全局函数中注入工厂? 有没有其他方法可以实现这一点,也许在app.config()内?

1 个答案:

答案 0 :(得分:5)

如果你的应用程序有一个Angular $injectorref),你可以轻松调用依赖注入的函数:

$injector.invoke(["$http", myfunction]);
例如,您可以将整个函数包装为:

app.onNotificationGCM = function (e) {
    $injector.invoke(["$http", function($http) {
        // your code here... it will be dependency injected by Angular
    }]);
};

您肯定希望拨打$apply() - $http之前不会运行的呼叫,所以代码应该是:

app.onNotificationGCM = function (e) {
    $injector.invoke(["$http", "$rootScope", function($http, $rootScope) {
        $rootScope.$apply(function() {
            // your code here... it will be dependency injected by Angular
            // ... AND called properly in a digest cycle
        });
    }]);
};

这只是第一部分。现在的问题是如何为您的申请获得适当的$injector

如果您手动引导,则angular.bootstrapref)将返回注入器。只需将其保存在(全局?)var。

您可能使用ng-app。然后你必须以某种方式识别包含ng-app的元素并调用angular.element.injectorref - 寻找&#34; jQuery / jqLit​​e Extras&#34;)。例如,如果ng-app中有<body>

// in code OUTSIDE Angular
var $injector = angular.element(document.body).injector();