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

时间:2017-09-19 10:22:36

标签: javascript angularjs json post angularjs-directive

我是角色新手,我正在尝试创建一个简单的注册表单,该表单发布到数据库(在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}}在某种程度上超出了此范围

2 个答案:

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