繁体   English   中英

AngularJS中的JS全局变量返回未定义

[英]JS Global Variable in AngularJS returns undefined

我正在尝试访问一些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时,其返回的值都是未定义的。 有什么想法吗?

因此,您尚未将其分配给全局变量。 您已将其分配给局部函数作用域变量。

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

您的regID服务不执行任何操作。 它应该返回$ window.regID。

总而言之,这不是正确的方法。 正确的方法是返回承诺的服务。 该服务还侦听本机javascript或jqlite事件,并在处理事件时解决承诺。

暂无
暂无

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

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