Call async service in AngularJS custom validation directive

前端 未结 2 1346
攒了一身酷
攒了一身酷 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:18

    In order to get this to work, I needed to add "return value;" outside of the asynchronous call. Code below.

    commonModule.directive("usernameVerify", [
        'userSvc', function(userSvc) {
            return {
                require: 'ngModel',
                scope: false,
                link: function(scope, element, attrs, ctrl) {
                    ctrl.$parsers.unshift(checkForAvailability);
                    ctrl.$formatters.unshift(checkForAvailability);
    
                    function checkForAvailability(value) {
                        if (value.length < 5) {
                            return value;
                        }
                        userSvc.userExists(value)
                            .success(function(alreadyUsed) {
                                var valid = alreadyUsed === 'false';
                                if (valid) {
                                    ctrl.$setValidity('usernameVerify', true);
                                    return value;
                                }
                                ctrl.$setValidity('usernameVerify', false);
                                return undefined;
                            });
                        // Below is the added line of code.
                        return value;
                    }
                }
            }
        }
    ]);
    
    0 讨论(0)
  • 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;
       });
    };
    
    0 讨论(0)
提交回复
热议问题