AngularJS does not update after value change

后端 未结 3 1156
没有蜡笔的小新
没有蜡笔的小新 2021-01-15 20:40

My intention is to update the navigation bar after the user login. Basically, it should change Login to Hi, {{usr.username}} right after the login.

相关标签:
3条回答
  • 2021-01-15 20:59

    AngularJS won't update the view if any changes to the $scope object are done outside of its $digest loop.

    But worry not, Firebase is such a popular tool it has a AngularJS service. It's called AngularFire and you should be using it instead of global Firebase object.

    So your code will be something similar to:

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

    Read more in the documentation of AngularFire

    0 讨论(0)
  • 2021-01-15 21:12

    Try calling $scope.$digest() right after changing $scope.usr value. Anyway, notice that you call to Firebase to get the user is asynchronous, so I wouldn't put dependent code after this call, but inside the callback.

    0 讨论(0)
  • 2021-01-15 21:13

    Call $scope.$apply();

    FirebaseRef.child("users").child(authData.uid).once('value', function(dataSnapshot) {
    
       $scope.$apply(function(){
          $scope.usr = dataSnapshot.val();
       });
    
    });
    
    0 讨论(0)
提交回复
热议问题