【问题标题】:Why won't this from scope variable at Angular JS controller is set to true?为什么 Angular JS 控制器的作用域变量不会设置为 true?
【发布时间】:2014-05-27 13:12:52
【问题描述】:

我正在尝试编写一个控制器,因此某些输入在另一个输入发生更改后会被禁用。

这是控制器:

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,但从未让它以这种方式工作

【问题讨论】:

  • 在某些时候this 可能不是你想的那样
  • 可能您正在尝试 John Papa 公开的这种奇怪方法,但您需要在 johnpapa.net/… 之前将其设置为 var
  • @Dalorzo 读完之后我真的不明白我应该做什么。你能在答案中解释一下吗?

标签: javascript angularjs


【解决方案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中就是这样处理的

【讨论】:

  • 你摇滚吧!有效。你能给我解释一下用苹果吗?将来可能会对其他学习者有所帮助
猜你喜欢
  • 1970-01-01
  • 2015-09-12
  • 2020-11-14
  • 1970-01-01
  • 2019-01-23
  • 1970-01-01
  • 2015-05-02
  • 1970-01-01
  • 2020-02-06
相关资源
最近更新 更多