Iva*_*nov 2 javascript dependency-injection angularjs cordova-3
我正在用angular.js编写一个cordova应用程序.当我使用PushPlugin向用户发送推送通知时.我已经注册了这样的用户手机:
var pushNotification = window.plugins.pushNotification;
pushNotification.register(successHandler, errorHandler, { "senderID": [gmc_project_number], "ecb": "app.onNotificationGCM" });
Run Code Online (Sandbox Code Playgroud)
我传递的最后一个参数是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;
}
};
Run Code Online (Sandbox Code Playgroud)
我必须将它添加到全局变量(在本例中为angular.module)中,以便在返回响应时可以访问它.
这是我从https://github.com/phonegap-build/PushPlugin/issues/309得到的解释
因为Android JAVA代码调用一个名为sendJavascript()的函数(我在LogCat中看到它),这个函数包含一个字符串,其中包含在文档中调用的onNotificationGCM(Json)函数,所以如果你在"onDeviceReady"中加载函数只有当设备准备好并且不总是那样的时候它才是可用的(注册需要几秒钟才能回来)
因为现在它工作得很好.问题是我想调用一个工厂并从里面发出一个http调用onNotificationGCM.目前我不知道如何注射工厂.我尝试将onNotificationGCM函数分配给$rootScope但是在响应中无法访问.
有没有办法在这个全局函数中注入工厂?有没有其他方法可以实现这一点,也许在里面app.config()?
如果您的应用程序有一个Angular $injector(ref),则可以轻松调用依赖注入的函数:
$injector.invoke(["$http", myfunction]);
Run Code Online (Sandbox Code Playgroud)
例如,您可以将整个函数包装为:
app.onNotificationGCM = function (e) {
$injector.invoke(["$http", function($http) {
// your code here... it will be dependency injected by Angular
}]);
};
Run Code Online (Sandbox Code Playgroud)
你肯定会想要调用$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
});
}]);
};
Run Code Online (Sandbox Code Playgroud)
那只是第一部分.现在的问题是如何掌握适用$injector于您的应用程序?
如果手动引导,则angular.bootstrap(ref)返回注入器.只需将其保存在(全局?)变量中.
你可能会用ng-app.然后你必须识别包含ng-app某种方式的元素并调用angular.element.injector(ref - 查找"jQuery/jqLite Extras").例如,如果ng-app在<body>:
// in code OUTSIDE Angular
var $injector = angular.element(document.body).injector();
Run Code Online (Sandbox Code Playgroud)