2016-01-24 83 views
0

所需的指令顯示紅色的錯誤消息,工作! uniqueschoolclassnumberValidator指令不顯示紅色錯誤消息!錯誤消息與AsyncValidator不可見

從服務器我總是返回exists => true,但我也試着用false。

我該怎麼做?自定義指令肯定會觸發!

指令

'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> 

回答

0

在服務的存在的方法有應該回報關鍵字$ q.reject前:

if (response.data == true) { 
    return $q.reject("schoolclass number has already been taken"); 
} 
else { 
    return $q.resolve(); 
} 

指令應該被命名爲uniqueSchoolclassnumberValidator,而不是uniqueschoolclassnumberValidator(AngularJS改變劃線分隔的格式,以駝峯)。

在html代碼中還有拼寫錯誤,在單詞「class」中。它應該是unique-schoolclassnumber-Validator而不是unique-schoolclasnumber-Validator

+0

拼寫錯誤來自我在這裏所做的複製/粘貼錯誤。但該死的是,返回失蹤,我剛剛沒有看到它!現在它工作了! – HelloWorld