2014-09-04 101 views
0

我試圖訪問一些JavaScript中的值以便在AngularJS服務中使用。我已經成功地將值存儲在變量中,但是我有問題將該變量放入我的AngularJS服務中。這裏是我的代碼:AngularJS中的JS Global變量返回undefined

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回來爲未定義。任何想法爲什麼?

+1

請查看術語「全局變量」。 – user2864740 2014-09-04 22:22:35

+0

[在JavaScript函數中定義全局變量]的可能重複(http://stackoverflow.com/questions/5786851/define-global-variable-in-a-javascript-function) – user2864740 2014-09-04 22:23:56

+0

雖然它可能是XY問題(全局變量,特別是異步操作,* * * *),該問題包含「答案」。 – user2864740 2014-09-04 22:24:24

回答

0

所以你還沒有把它分配給一個全局變量。您已將其分配給本地函數作用域變量。

要將其分配給全局變量,請使用window.regID而不是var regID。

您的regID服務無所作爲。它應該返回$ window.regID。

這一切都說,這不是正確的做法。正確的做法是返回承諾的服務。該服務還會監聽原生javascript或jqlite事件,並在處理事件時解決承諾。

+0

你有沒有任何關於如何讓我的服務如你所說的做法,我的角度知識是非常有限的。謝謝你的迴應 – geolaw 2014-09-04 23:08:55

+0

這已經成功了。謝謝讓我陷入了一段時間。非常感激。 – geolaw 2014-09-04 23:20:12

+0

@geolaw讓我知道什麼事件觸發onNotification()處理程序,我會更新服務。你想要擺脫的另一件事是控制器中的$()。append()DOM操作。應使用在視圖或ngMessage中爲1.3顯示的範圍變量。 – Martin 2014-09-05 07:46:41