只需执行以下操作:
$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条件之后编写after,但是有时会引发异常,
digest cycle isalready inprogress因为调用
$scope.$apply(),我们会手动触发Angular的摘要周期。这就是为什么
$timeout服务更清洁的原因。
更新资料
请注意,您根本不需要使用jQuery来进行AJAX调用。Angular提供
$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 });};


