使用angular 1.3 ngMessage表单提交错误

时间:2014-11-06 21:00:45

标签: javascript angularjs forms

我已经在我的应用中为登录页面正确地运行了表单验证示例,如下所示:

 <div class="form-group" >
            <label for="password">Password</label>
            <input type="password"
                   id="password"
                   name="password"
                   class="form-control"
                   placeholder="Create password"
                   ng-model="password"
                   required
                   minlength="{{passwordLength}}"
                   >
            <div class="help-block text-danger"
                 ng-messages="form.password.$error"
                 ng-if="form.password.$touched || form.$submitted"
                 >
              <div class="text-danger">
                <div ng-message="required">A password is required</div>
                <div ng-message="minlength" >Password must be at least {{passwordLength}} characters</div>
              </div>

            </div>
          </div>

这适用于&#34;必需&#34;和&#34; minlength&#34;检查,可以在提交之前完成。但是,在提交后,我们可以获取401用于无效的用户名/密码。 Angular 1.3有一个异步验证概念,但它似乎在提交之前运行,尝试登录两次似乎是不合理的(一次只是为了看看它们是否可以并提示错误)

是否有合理的方法使用ng-messages概念来显示此提交后错误?

1 个答案:

答案 0 :(得分:6)

我明白了。您只需手动验证/使表单无效:

<div class="help-block text-danger">
            <div class="text-danger"
                 ng-messages="form.password.$error"
                 ng-if="form.password.$touched || form.$submitted">
              <div ng-message="required">Password is required</div>
              <div ng-message="minlength">*Password must be at least {{passwordLength}} characters</div>
              <div ng-message="correctPassword">Username/Password combination is incorrect</div>
            </div>
          </div>

并在您的控制器中,提交时:

 $scope.login = function(){
    $scope.form.password.$setValidity("correctPassword", true);
    // ...do some stuff...
    $http.post('/someUrl', {msg:'hello word!'})
      .success(function(){})
      .error(function() {
         $scope.form.password.$setValidity("correctPassword", false);
  });
 }