gpt4 book ai didi

javascript - 未从 $http 范围设置 Angular 绑定(bind)变量

转载 作者:行者123 更新时间:2023-11-28 14:46:15 25 4
gpt4 key购买 nike

我是 Angular 新手,我正在尝试创建一个简单的注册表单,该注册表单会发布到数据库(以 json 格式)。

如果数据库写入成功,“this.msg”将被设置为“发布数据提交成功!”

如果数据库写入不成功,“this.msg”将被设置为“Service does not Exists”

<row ng-controller="appController as app">
<div>
Username : <input ng-model="app.regUsername" />
Password : <input ng-model="app.regPassword" />
<input type="button" value="Register" ng-click="app.postdata(app.regUsername, app.regPassword)" />
</div>
<p>Output Message :{{app.msg}}</p>
</row>

但是我无法让 this.msg 在 HTML 中打印出来。一切似乎都工作正常,没有控制台错误,this.msg 存在,数据库写入正常。

app.controller('appController', ['$http', function ($http) {
this.name = null;
this.password = null;

this.postdata = function (name, password) {

var data = {
name: name,
password: password
};

$http.post('https://my-project.com/.json', JSON.stringify(data)).then(function (response) {
if (response.data){
this.msg = "Post Data Submitted Successfully!";
console.log(this.msg) //works fine;
}
}, function (response) {
this.msg = "Service does not Exists";
console.log(this.msg) //works fine
});
};

我只能推测存在范围问题,并且 {{app.msg}} 超出了此范围

最佳答案

您需要将作用域分配给另一个变量,this 是在 post() 的上下文中执行的

试试这个

app.controller('appController', ['$http', function ($http) {
self = this; // <-- add this
self.name = null;
self.password = null;

self.postdata = function (name, password) {

var data = {
name: name,
password: password
};

$http.post('https://my-project.com/.json',
JSON.stringify(data)).then(function (response) {
if (response.data){
self.msg = "Post Data Submitted Successfully!";
console.log(self.msg) //works fine;
}
}, function (response) {
self.msg = "Service does not Exists";
console.log(self.msg) //works fine
});
};

关于javascript - 未从 $http 范围设置 Angular 绑定(bind)变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46297987/

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