0

我正在尝试访问一些 Javascript 中的值以在 AngularJS 服务中使用。我已经成功地将值存储在一个变量中,但是我在将该变量放入我的 AngularJS 服务时遇到了问题。这是我的代码:

JS函数:

 function onNotification(e) {

$("#app-status-ul").append('<li>EVENT -> RECEIVED:' + e.event + '</li>');

switch( e.event )
{
case 'registered':
    if ( e.regid.length > 0 )
    {
        $("#app-status-ul").append('<li>REGISTERED -> REGID:' + e.regid + "</li>");
        // Your GCM push server needs to know the regID before it can push to this device
        // here is where you might want to send it the regID for later use.

        var regid = e.regid
        console.log(regid);
    }
break;

变量 regid 是我想要访问的。

AngularJS 服务:

App.service('regID', function()
{
return{}
});

角函数:

App.controller('MainCtrl', function($scope, $state, regID, $window){
console.log('MainCtrl');

var pushNotification;

document.addEventListener("deviceready", onDeviceReady, false);

$scope.regID = regID;
$scope.regID.regID = $window.regid;
console.log($scope.regID);

function onDeviceReady()
{   
    pushNotification = window.plugins.pushNotification;
    $("#app-status-ul").append('<li>registering ' + device.platform + '</li>');

    if ( device.platform == 'android' || device.platform == 'Android'){

        pushNotification.register(
        successHandler,
        errorHandler,
        {
            "senderID":"460885134680",
            "ecb":"onNotification",
        });
    } else {
        pushNotification.register(
        tokenHandler,
        errorHandler,
        {
            "badge":"true",
            "sound":"true",
            "alert":"true",
            "ecb":"onNotificationAPN"
        });
    }
}

function successHandler (result, $scope, regID, $window)
{
    alert('result = ' + result);
}

function errorHandler (error)
{
    alert('error = ' + error);
}   
});

每次我运行这个 $window.regid 时都会返回未定义。关于为什么的任何想法?

4

1 回答 1

0

因此,您尚未将其分配给全局变量。您已将其分配给本地函数范围变量。

要将其分配给全局变量,请使用 window.regID 而不是 var regID。

您的 regID 服务什么都不做。它应该返回 $window.regID。

综上所述,这不是正确的方法。正确的方法是返回一个承诺的服务。该服务还侦听本机 javascript 或 jqlite 事件,并在处理事件时解析承诺。

于 2014-09-04T22:47:40.177 回答