Call async service in AngularJS custom validation directive

前端 未结 2 1347
攒了一身酷
攒了一身酷 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;
                    }
                }
            }
        }
    ]);
    

提交回复
热议问题