我是角色新手,我正在尝试创建一个简单的注册表单,该表单发布到数据库(在json中)。
如果数据库写入成功,则“this.msg”设置为“发布数据成功提交!”
如果数据库写入失败,则“this.msg”设置为“Service not 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>
但是我不能把这个.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}}在某种程度上超出了此范围
答案 0 :(得分:3)
您需要将范围指定给另一个变量,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
});
};
答案 1 :(得分:1)
试试这个
app.controller('appController', ['$http', function ($http) {
this.name = null;
this.password = null;
var appCtrl = this;
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) {
appCtrl.msg = "Post Data Submitted Successfully!";
console.log(appCtrl.msg) //works fine;
}
}, function (response) {
appCtrl.msg = "Service does not Exists";
console.log(appCtrl.msg) //works fine
});
};