AngularJS ng-class和表单验证行为

时间:2015-08-19 09:47:46

标签: angularjs twitter-bootstrap-3 ng-class

有一个非常严重的问题,我认为该问题应该有效,但不应该表现得如此:

<div class="form-group" ng-class="{'has-error': !emailstatus && userBooking.email.$dirty, 'has-success': emailstatus}">
    <div class="col-md-12 col-sm-12 col-lg-12 col-xs-12">

        <input class="form-control input-lg" name="email" type="text"placeholder="Mail" ng-model="formData.email" ng-change="email()">
        <label style="margin-top:-8px;"> Ange mailadress</label></br>{{emailmessage}}
    </div>
</div>

简单的表单验证,我有一个函数email(),它检查电子邮件字段中写的电子邮件是否已经存在于数据库中,然后应该将表单设置为错误,但这只有在有人触摸表单时才会发生。

然而它的行为并不那样,成功很好,因为电子邮件不在数据库中而变成绿色

enter image description here

当没有人写任何东西时,它在开头是灰色的。

From the beginning

但是,只要电子邮件在数据库中,表单就会变成灰色而不是红色?但是当检查变量emailstatus时,它肯定是“假的”,因此在表达式中应该是真的。 It IS already in the database but the form is grey instead of red?

最后,如果我将ng-class表达式改为:

,那就更奇怪了
   {'has-error': !emailstatus, 'has-success': emailstatus}

它按预期工作,除非用户没有触摸它($ pristine)它是红色的不可接受的原因。

Working but is red even if it is $pristine

Angular function email():

 var checkEmail = function() {
    params = {
        email: $scope.formData.email
    };

    $http({
            method: 'POST',
            url: 'php/emailcheck.php',
            data: $.param(params), // pass in data as strings
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            } // set the headers so angular passing info as form data (not request payload)
        })
        .success(function(data) {
            if (!data) {
                // if not successful, bind errors to error variables
                console.log("error");
            } else {
                if (data === "Yes") {
                    $scope.emailmessage = "Adressen finns redan registrerad, vänligen välj en annan."
                    $scope.emailstatus = false

                } else if (data === "No") {
                    $scope.emailmessage = "Adressen är ledig!"
                    $scope.emailstatus = true
                } else {
                    console.log("nothing happens if the code is wrong")
                }
            }
        });
};

1 个答案:

答案 0 :(得分:0)

解决此问题:

它按预期工作,除非用户没有碰到红色这是不可接受的原因($ pristine)

也使用$触及属性(&gt; =仅Angular 1.3)。

这将确保仅在输入为:

时才启动验证
  • 无效
  • 用户点击了输入(即触摸了它)