AsyncValidator的错误消息不可见

时间:2016-01-24 17:31:45

标签: angularjs

必需的指令显示有效的红色错误消息! uniqueschoolclassnumberValidator指令显示NOT红色错误消息!

从服务器我总是返回exists =>是的,但我也尝试过它。

我错了什么?肯定会触发自定义指令!

指令

 'use strict';
angular.module('TGB').directive('uniqueschoolclassnumberValidator', function (schoolclassCodeService) {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ngModel) {
            ngModel.$asyncValidators.unique = function (schoolclass) {
                var schoolclassNumber = "0a";
                var schoolyearId = 1;
                return schoolclassCodeService.exists(schoolyearId, schoolclassNumber);
            };
        }
    };
});

服务

this.exists = function (schoolyearId, schoolclassNumber) {

      var path = 'api/schoolyears/' + schoolyearId + '/schoolclasses/' + schoolclassNumber;
      return $http.get(path).then(function (response) {
          if (response.data == true) {
              $q.reject("schoolclass number has already been taken");
          }
          else {
              return $q.resolve();
          }
      });
  };

HTML

<form name="myForm">
    <div class="col-sm-8">
        <input type="text" unique-schoolclasnumber-Validator name="myInput" 
               ng-model-options="{ updateOn: 'default blur', debounce: {'default': 300, 'blur': 0} }"
               ng-model="schoolclassNumber" class="form-control" 
               required placeholder="Enter schoolclass">
    </div>
    <div ng-messages="myForm.myInput.$error" style="color:red" role="alert">
        <div ng-message="required">You did not enter anything.</div>
        <div ng-message="unique">That schoolclass number already exists.</div>
    </div>
</form>

1 个答案:

答案 0 :(得分:0)

在你的服务的exists方法中,$ q.reject:

之前应该有return关键字
if (response.data == true) {
     return $q.reject("schoolclass number has already been taken");
}
else {
     return $q.resolve();
}

指令应命名为uniqueSchoolclassnumberValidator而不是uniqueschoolclassnumberValidator(AngularJS将划线分隔格式更改为camelCase)。

html代码中也有一个拼写错误,单词“class”。它应该是unique-schoolclassnumber-Validator而不是unique-schoolclasnumber-Validator