2016-07-31 5 views
0

내 $ scope.key에이 함수 밖에서 어떻게 액세스 할 수 있습니까?

.controller('CatsCtrl', function($scope, $state, $http) { 

     var query = firebase.database().ref().orderByKey(); 
     query.once("value") 
     .then(function(snapshot) { 
      snapshot.forEach(function(childSnapshot) { 
      $scope.key = childSnapshot.key; 
      // I need this value 
      $scope.childData = childSnapshot.val(); 

      $scope.data = $scope.childData.Category; 

      console.log($scope.key); 
      }); 
     }); 

     console.log($scope.key); 
     // returns undefined 

     var ref = firebase.database().ref($scope.key); 
      ref.once("value") 
      .then(function(snapshot) { 
       console.log(snapshot.val()); 
       var name = snapshot.child("Category").val(); 
       console.log(name); 
      }); 
    }) 

$ scope.apply를 사용해 보았지만 제대로 작동하지 않았습니다. 당신이 당신의 두 번째 통화에 childSnapshot.key 필요 못했을 경우에 대비

+0

함수가 실행 된 후에'$ scope.key' –

+0

no에 접근 할 수 있습니다. 어떤 이유로 함수가 실행 된 후에도 정의되지 않았습니다. – olivier

+0

전체 컨트롤러 코드보기 –

답변

2

, 당신은 약속 성공 콜백에 액세스해야 다음 childSnaphot 객체가 forEach 콜백에 있기 때문에이 각 반복에 대해 실행됩니다

query.once("value") 
    .then(function(snapshot) { 
     snapshot.forEach(function(childSnapshot) { 
     $scope.childData = childSnapshot.val(); 

     $scope.data = $scope.childData.Category; 

     var ref = firebase.database().ref(childSnapshot.key); 
     ref.once("value") 
      .then(function(snapshot) { 
      console.log(snapshot.val()); 
      var name = snapshot.child("Category").val(); 
      console.log(name); 
     }); 
     }); 
    }); 

관련 문제