angularjs消息绑定不会显示,直到第二个表单提交

时间:2015-01-09 00:11:06

标签: javascript angularjs firebase

我正在编写我的第一个angularjs应用程序,它开始有意义了。但是,我有一个注册表单,在某些情况下没有获取消息以提醒用户出现问题。我正在使用Firebase进行身份验证,工作正常。但我用一个唯一的用户名作为密钥来存储用户。所以在我运行$createUser函数之前,我会快速查询是否已经有一个带有此键的用户对象 - 如果没有,我创建用户。

问题是当现有用户具有此用户名时。控制台日志值打印正常,但错误消息(绑定到$scope.authMsg)没有第一次显示 - 但如果我再次单击“注册”按钮,则消息显示在预期的消息中DIV。

有关消息问题的任何提示(或对此代码的建议)将不胜感激!

$scope.register = function() {
    $scope.authMsg = '';
    var ref = new Firebase(FIREBASE_URL);
    $scope.authObj = $firebaseAuth(ref);

    // check if the username is taken
    ref.child("/users/"+$scope.account.username).on("value", function(snapshot) {
        if (snapshot.val()) {
            //
            // PROBLEM HERE!!
            //
            $scope.authMsg = 'Username exists-- did you forget your password?'; // doesn't show on page until second submit
            console.log('Username exists-- did you forget your password?'); // prints to console as expected
        } else {
            $scope.authObj.$createUser({ email: $scope.account.email, password: $scope.account.password })
            .then(function(userData) {
                console.dir(userData);
                return $scope.authObj.$authWithPassword({
                    email: $scope.account.email,
                    password: $scope.account.password
                });
            }).then(function(authData) {
                // we created a user and are now logged in-- store user info
                var userdata = {};
                userdata[$scope.account.username] = {
                                uid: authData.uid,
                                first_name: $scope.account.first_name,
                                last_name: $scope.account.last_name,
                                email: $scope.account.email,
                                full_name: $scope.account.first_name+' '+$scope.account.last_name
                            };
                var usersRef = ref.child("users");
                // save the userdata
                usersRef.set(userdata);
                console.log("Logged in as:", authData.uid);
                $state.go('app.dashboard');
            }).catch(function(error) {
                $scope.authMsg = error;
                console.error("Error: ", error);
            });
        }
    }, function (errorObject) {
        $scope.authMsg = 'The read failed: ' + errorObject.code;
        console.log('The read failed: ' + errorObject.code);
    });
};

1 个答案:

答案 0 :(得分:2)

我假设,Firebase回调不涉及角度摘要周期。

要处理此问题,请写

if (snapshot.val()) {
    $scope.$apply(function() {
        $scope.authMsg = 'Username exists— did you forget your password?';
    });

关于该主题的有用阅读:http://jimhoskins.com/2012/12/17/angularjs-and-apply.html