Call async service in AngularJS custom validation directive

前端 未结 2 1361
攒了一身酷
攒了一身酷 2021-01-02 12:37

I have a directive for custom validation (verify a username doesn\'t already exist). The validation uses the $http service to ask the server if the username exists, so the

2条回答
  •  渐次进展
    2021-01-02 13:21

    Angular has a dedicated array of $asyncValidators for precisely this situation:

    see https://docs.angularjs.org/api/ng/type/ngModel.NgModelController

    ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
    var value = modelValue || viewValue;
    
    // Lookup user by username
    return $http.get({url:'/api/users/' + value}).
       then(function resolved() {
         //username exists, this means validation fails
         return $q.reject('exists');
       }, function rejected() {
         //username does not exist, therefore this validation passes
         return true;
       });
    };
    

提交回复
热议问题