gpt4 book ai didi

javascript - 直到第二个表单提交后,AngularJS消息绑定(bind)才会显示

转载 作者:行者123 更新时间:2023-12-02 16:36:58 25 4
gpt4 key购买 nike

我正在编写我的第一个 angularjs 应用程序,它开始有意义了。但是,我有一个注册表单,在某些情况下无法收到提醒用户出现问题的消息。我正在使用 Firebase 进行身份验证,效果很好。但我通过唯一的用户名作为 key 来存储用户。所以在我运行 $createUser 之前函数中,我进行快速查询以查看是否已经存在具有此键的用户对象 - 如果没有,我将创建该用户。

问题在于现有用户使用此用户名。控制台日志值打印正常,但错误消息(绑定(bind)到 $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);
});
};

最佳答案

我假设 Firebase 回调不涉及 Angular 摘要循环。

要处理这个问题,请编写

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

关于javascript - 直到第二个表单提交后,AngularJS消息绑定(bind)才会显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27851838/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com