我試圖訪問一些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回來爲未定義。任何想法爲什麼?
請查看術語「全局變量」。 – user2864740 2014-09-04 22:22:35
[在JavaScript函數中定義全局變量]的可能重複(http://stackoverflow.com/questions/5786851/define-global-variable-in-a-javascript-function) – user2864740 2014-09-04 22:23:56
雖然它可能是XY問題(全局變量,特別是異步操作,* * * *),該問題包含「答案」。 – user2864740 2014-09-04 22:24:24