在其他函数中访问$ scope

时间:2016-07-31 15:14:28

标签: angularjs ionic-framework firebase firebase-realtime-database

如何在这个函数中访问我的$ 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,但这不起作用。

1 个答案:

答案 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回调