只需执行以下操作:注入$timeout
在您的控制器中提供服务并包装您的代码,如下所示:
complete: function(response) {
console.log(response.responseText);
$timeout(function() {
if (response.responseText == 'success') {
console.log('Registration Success');
alert('Success');
$scope.msgalert = 'Registration Success, Proceed to Login and Continue';
} else if (response.responseText == 'fail') {
alert('registration failed');
$scope.msgalert = 'Registration Failed, Please try again';
}
});
}
另外,更改您的 HTML 代码,如下所示:
<h3 ng-show="msgalert"><em>{{msgalert}}</em></h3>
所以Angular中就有了消化循环的概念。如果您正在 Angular 上下文之外执行某些操作(例如您正在使用 jQuery AJAX 来获取数据并更新 $scope 变量)msgalert
),我们必须告诉 Angular 数据发生了变化。
因此,在收到服务器的响应并更新后msgalert
,Angular 不知道该更改,因为它位于 Angular 上下文之外,因此会触发 Angular 新的摘要周期,并且视图不会更新。
为什么你会看到这个,当你再次点击表单中的提交按钮时,Angular 的摘要循环会在幕后触发,然后你的实际消息就会显示出来。
为了解决这个问题,我们使用以下方法将您的自定义(角度上下文之外)代码包装到 Angular 的上下文中:$timeout
立即通知 Angular 中的值的服务msgalert
已经改变
或者,您可以编写$scope.$apply()
在你之后if-else
条件但有时会引发异常digest cycle is already in progress
因为打电话$scope.$apply()
,我们手动触发 Angular 的摘要周期。这就是为什么更清洁的方法是$timeout
服务。
Update
请注意,您根本不必使用 jQuery 来执行 AJAX 调用。角有$http
服务并使用它,您根本不会遇到这个问题。你可以这样写你的代码:
$scope.submitForm = function (isValid, user) {
var regData = {
email: user.email,
password: user.password1
};
$http({
method: "POST",
url: "myurl",
data: regData, // You don't need to stringify it and no need to set any headers
}).then(function (response) {
// Success callback
console.log(response.responseText);
if (response.responseText == 'success') {
$scope.msgalert = 'Registration Success, Proceed to Login and Continue';
} else if (response.responseText == 'fail') {
$scope.msgalert = 'Registration Failed, Please try again';
}
}, function() {
// Error callback
});
};