olivier olivier - 4 months ago 11
AngularJS Question

Access $scope in other function

How can i access my $scope.key out side this function?

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


I've tried it with $scope.apply but this did not work.

Answer

Incase you need the childSnapshot.key in your second call, you should access it in the promise success callback:

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

Note that this will run for each iteration since the childSnaphot object is in the forEach callback

Comments