栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

AngularJS与Ajax表单提交需要单击两次

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

AngularJS与Ajax表单提交需要单击两次

只需执行以下操作:

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/399798.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号