【问题标题】:Firebase Database Function Can't Modify a $scope variable in angularjsFirebase 数据库函数无法修改 angularjs 中的 $scope 变量
【发布时间】:2016-11-23 18:56:16
【问题描述】:

我有以下代码:

angular.module("MyApp", ['textAngular'])
.controller("demoController", function demoController($scope) {
    $scope.content = null;
    firebase.database().ref('pages/home').on('value', function(snapshot) { $scope.content = snapshot.val(); });
    console.log($scope.content);
});

如您所见,我要做的只是在访问 firebase 数据库的函数中更改控制器范围内的变量,以便存储某个条目的内容。然而,当尝试这样做时,变量根本不会改变。我尝试过使用“window.content”,以及尝试使用“var content;”做同样的事情。无济于事。有什么方法可以让一个变量在函数内被全局访问?

edit - 当我运行 firebase.databse().ref 函数并使用 alert(snapshot.val());它可以工作,并且信息会显示在警报中。

【问题讨论】:

    标签: javascript angularjs firebase firebase-realtime-database


    【解决方案1】:

    Firebase 是异步的,(即剩下的代码不用等待firebase 函数运行就可以运行。把console.log 放在on 函数里面,你会看到范围变量实际上已经改变了。

    【讨论】:

      【解决方案2】:

      使用$apply():

      $apply() 用于从外部执行角度表达式 Angular 框架(例如来自浏览器 DOM 事件、setTimeout、XHR 或第三方库)。

      例如:

      firebase.database()
        .ref('pages/home')
        .on('value', function(snapshot) {     
          $scope.$apply(function(){
            $scope.content = snapshot.val();
          });
      });
      

      【讨论】:

      • 尝试这个后,变量仍然无法识别,记录时返回null。
      【解决方案3】:

      试试这个

      firebase.database().ref('pages/home').on('value', function(snapshot) {     scope.$apply(function(){$scope.content = snapshot.val().content });});
      

      【讨论】:

        【解决方案4】:

        这些方法都不起作用,但是我最终通过这样做解决了问题:

        var app = angular.module("textAngularDemo", ['textAngular'])
        app.controller("demoController", function demoController($scope) {
            firebase.database().ref('pages/home').on('value', function(snapshot) {     
                test($scope, snapshot.val());
            });
            $scope.detectChange = function(){
                setTimeout(function(){
                    if ($scope.content)
                    {
                        console.log ($scope.content);
                        }
                    }
                    else
                    {
                        $scope.detectChange();
                    }
                }, 1);
            }
            function test(scope, variable){
                scope.content = variable;
                $scope.$apply();
            }
            setTimeout(function(){ $scope.detectChange() }, 1);
        });
        

        我相信这与承诺的行为方式相同,但是我当时不知道如何实现它们。如果你愿意,可以称之为“伪承诺”。

        【讨论】:

          猜你喜欢
          • 2021-08-20
          • 1970-01-01
          • 2017-08-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-12-20
          • 2015-10-22
          • 1970-01-01
          相关资源
          最近更新 更多