【问题标题】:AngularJS does not update after value change值更改后AngularJS不更新
【发布时间】:2014-11-19 08:08:48
【问题描述】:

我的目的是在用户登录后更新导航栏。基本上,它应该在登录后立即将Login 更改为Hi, {{usr.username}}
但是,登录后它不会更新,我必须再次单击Login 才能触发更改。但是,在控制台中,用户信息会在登录后立即记录。

在index.html中,部分代码如下:

<div class="item" ng-click="loginmodal()" ng-hide="loggedIn">Log in</div>
<div class="item" ng-show="loggedIn">Hi, {{usr.username}}</div>

$scope.loggedIn 被初始化为 false,$scope.usr 被初始化为 null。我正在使用 firebase 进行身份验证:

FirebaseRef.authWithPassword({
    "email"    : email,
    "password" : password
}, function(error, authData) {
    if (error) {
        console.log('Login Failed!', error);
    } else {
        console.log('Authenticated successfully with payload:', authData);
        FirebaseRef.child("users").child(authData.uid).once('value', function(dataSnapshot) {
            $scope.usr = dataSnapshot.val();
        });

        $scope.loggedIn = true;

        console.log($scope.usr);
        console.log($scope.loggedIn);
    }
});

在控制台中,我将 $scope.loggedIn 设为 true,但将 $scope.usr设为 null。

我使用authWithPassword() 函数的方式有问题还是我可以强制更新更改?

【问题讨论】:

  • 我认为 $scope.user 在另一个范围内,请尝试使用服务来更新此值。
  • 正如@Miszy 所说,您应该使用AngularFire 的$firebaseAuth 服务,它会为您处理范围的更新。见firebase.com/docs/web/libraries/angular/…

标签: angularjs firebase angularfire


【解决方案1】:

如果对 $scope 对象的任何更改是在其 $digest 循环之外完成的,AngularJS 将不会更新视图。

但不用担心,Firebase 是如此受欢迎的工具,它拥有 AngularJS 服务。它被称为 AngularFire,您应该使用它而不是全局 Firebase 对象。

所以你的代码将类似于:

var auth = $firebaseAuth(FirebaseRef);
auth.$authWithPassword({
    email: email,
    password: password
}).then(function (authData) {
    console.log('Authenticated successfully with payload:', authData);
    var sync = $firebase(FirebaseRef.child("users").child(authData.uid));
    var syncObject = sync.$asObject();
    syncObject.$bindTo($scope, "usr");
}).catch(function (error) {
    console.error('Login Failed!', error);
});

阅读更多in the documentation of AngularFire

【讨论】:

    【解决方案2】:

    尝试在更改$scope.usr 值后立即调用$scope.$digest()。 无论如何,请注意您调用 Firebase 以获取用户是异步的,因此我不会将依赖代码放在此调用之后,而是放在回调中。

    【讨论】:

    • 我试过 $digest 和 $apply。都没有工作......现在工作正常。我正在使用 AngularFire。
    【解决方案3】:

    调用$scope.$apply();

    FirebaseRef.child("users").child(authData.uid).once('value', function(dataSnapshot) {
    
       $scope.$apply(function(){
          $scope.usr = dataSnapshot.val();
       });
    
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多