为什么在Angular JS控制器中从范围变量获得此设置为true?

时间:2014-05-27 04:52:17

标签: javascript angularjs

我尝试编码控制器,以便在另一个输入发生变化后禁用某些输入。

这是控件:

app.controller('SignUpController',function ($scope, $http) {

    this.unavaliable = true

    this.userUnavaliable = function() {

        console.log(this.unavaliable)
        return this.unavaliable
    }

    this.userExists = function(mail) {

        if (mail) {

            var who = $http.get("/existingUsers/"+mail)

            who.success(function(data,status, headers, config) {
                if (data.mail) {
                    this.unavaliable = true
                    console.log(data.mail + " ya existe en la DB")
                }
                else{
                    this.unavaliable = false
                }
            });

            who.error(function(data, status, headers, config) {
                    alert("AJAX failed!");
            })
        }

    }

})

正如下面的标记所示,一个输入应该获得某个类,而另一个输入应该在unavaliable设置为true时被禁用。但即使我可以进入console.log(),变量也似乎永远不会成真。

这是我的标记:

<form class="form-inline" role="form">
  <div class="form-group">
    <input type="email" class="form-control input-lg" ng-model="signup.mail" placeholder="e-mail" ng-change="signup.userExists(signup.mail)" ng-class="{'has-error':signup.userUnavaliable()}">
  </div>
  <div class="form-group">
    <input type="password" class="form-control input-lg" placeholder="Contraseña" ng-nodel="signup.password">
  </div>
  <div class="checkbox">
    <label>
      <input type="checkbox" ng-model="signup.role" value="admin"> Administrador
    </label>
  </div>
  <button type="submit" class="btn btn-primary" ng-disabled="signup.unavaliable" >Registrar</button>
</form>

我尝试使用$scope代替this,但从未让它以这种方式工作

1 个答案:

答案 0 :(得分:1)

试试这个:

app.controller('SignUpController',function ($scope, $http) {
var that = this;
    that.unavaliable = true;

    that.userUnavaliable = function() {  
        console.log(that.unavaliable)
        return that.unavaliable
    }

    that.userExists = function(mail) {...

您的问题似乎与JS Context有关;在上面的示例中,它保存在that变量中。这就是在JOhn's Papa approach

中完成的方式