Angular 未从 $http 范围设置绑定变量

Angular binding variable not being set from $http scope

我是 angular 的新手,我正在尝试创建一个简单的注册表单,将其发布到数据库(在 json 中)。

如果数据库写入成功,"this.msg"设置为"Post Data Submitted Successfully!"

如果数据库写入不成功,"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>

但是我无法在 HTML 中打印出 this.msg。一切似乎工作正常,没有控制台错误,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}} 不知何故超出了这个范围

试试这个

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

您需要将范围分配给另一个变量,thispost()

的上下文中执行

试试这个

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