2014-09-04 3 views
0

AngularJS 서비스에서 사용할 일부 자바 스크립트 값에 액세스하려고합니다. 변수에 값을 성공적으로 저장했지만 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 내가 액세스를 시도하고있는 무슨이다 :

JS 기능 : 여기 내 코드입니다.

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

+0

[JavaScript 함수에서 전역 변수 정의] 가능한 복제본 (http://stackoverflow.com/questions/5786851/define-global-variable-in-a-javascript-function) – user2864740

+0

XY 문제 일 수 있지만 변수, 특히 비동기 연산의 경우 * ick *), 해당 질문에는 "대답"이 포함됩니다. – user2864740

답변

0

그래서 전역 변수에 할당하지 않았습니다. 로컬 함수 범위 변수에 할당했습니다.

전역 변수에 할당하려면 var regID 대신 window.regID를 사용하십시오.

regID 서비스는 아무런 효과가 없습니다. $ window.regID를 반환해야합니다.

이 모든 것이 올바른 방법이 아닙니다. 올바른 접근 방식은 약속을 반환하는 서비스입니다. 이 서비스는 또한 네이티브 javascript 또는 jqlite 이벤트를 수신하고 이벤트가 처리 될 때 약속을 해결합니다.

+0

당신은 당신이 말한대로 나의 서비스를 만드는 방법의 어떤 exmarples을 가지고 있습니까, 각도에 대한 나의 지식은 극히 제한되어 있습니다. 응답을 주셔서 감사합니다 – geolaw

+0

이것은 트릭을 완료했습니다. 감사합니다. 매우 감사. – geolaw

+0

@geolaw 어떤 이벤트가 onNotification() 핸들러를 트리거하는지 알려 주면 서비스를 업데이트 할 것입니다. 제거하고자하는 또 다른 일은 컨트롤러에서 $(). append() DOM 조작입니다. 뷰에 표시되는 범위 변수 또는 1.3의 ngMessage를 사용해야합니다. – Martin

관련 문제