2016-07-31 42 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試過了,但是這沒有奏效。

+0

函數運行後,您可以訪問'$ scope.key' –

+0

否,出於某種原因,在函數運行之後它也是未定義的。 – olivier

+0

向我們展示完整的控制器代碼 –

回答

2

櫃面你在你的第二個電話需要childSnapshot.key,你應該訪問它的諾言成功回調:

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); 
     }); 
     }); 
    }); 

請注意,這會爲每個迭代運行,因爲childSnaphot對象是在forEach回調