【问题标题】:Access $scope in other function在其他函数中访问 $scope
【发布时间】:2016-08-01 00:25:12
【问题描述】:

如何在这个函数之外访问我的 $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 试过了,但这没有用。

【问题讨论】:

  • 函数运行后可以访问$scope.key
  • 不,由于某种原因,在函数运行后它也未定义。
  • 向我们展示完整的控制器代码
  • 更新了问题...
  • 你运行的函数是异步的,它会在你的console.log语句之后运行

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


【解决方案1】:

如果您在第二次调用中需要 childSnapshot.key,您应该在 promise 成功回调中访问它:

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 回调中,因此每次迭代都会运行此操作

【讨论】:

    猜你喜欢
    • 2020-04-13
    • 1970-01-01
    • 1970-01-01
    • 2018-03-07
    • 1970-01-01
    • 2018-04-03
    • 1970-01-01
    • 2021-05-20
    • 2017-10-28
    相关资源
    最近更新 更多