AngularJS名称可用性

时间:2015-10-22 08:52:36

标签: javascript angularjs

我有以下指令来检查用户名可用性。但无论服务器的返回结果如何,表单仍然禁用了提交按钮。

var app = angular.module('app', []);

app.controller('MainCtrl', function($scope, $http) {
  $scope.name = 'World';

});
    myApp.directive('verifyStore', function($timeout, $q, $http) {
      return {
        restrict: 'AE',
        require: 'ngModel',
        link: function(scope, elm, attr, model) { 
          model.$asyncValidators.usernameExists = function() { 
            //here you should access the backend, to check if username exists
            //and return a promise
             return $http.get('/api/verifystore').then(function(res){
              $timeout(function(){
                model.$setValidity('usernameExists', true); ---> or false button still disabled
              }, 1000);
            }); 
          };

        }
      } 
    });

    <div class="form-group">
        <input type="text" verify-store ng-model="storename" class="form-control" name="merchant.store_name" placeholder="Store Name" ng-model-options="{ updateOn: 'blur' }" required>
        <div ng-if="signupForm.$pending.usernameExists">checking....</div>
        <div ng-if="signupForm.$error.usernameExists">username exists already</div>
        </div>

提交按钮

<button type="submit" ng-disabled="signupForm.$invalid" class="btn btn-primary pull-right">
                            Submit <i class="fa fa-arrow-circle-right"></i>
                        </button>

谢谢!

2 个答案:

答案 0 :(得分:0)

当用户名存在时,您的承诺需要拒绝。

     model.$asyncValidators.usernameExists = function() { 
         return $http.get('/api/verifystore').then(function(res){
             return res ? $q.reject('that username exists') : res;
         }); 
      };

来源:https://docs.angularjs.org/api/ng/type/ngModel.NgModelController# $ asyncValidators

答案 1 :(得分:0)

如果您的服务器接受了用户名,则必须解决该承诺。 您只需返回true即可完成此操作。 如果用户名已经存在,你必须拒绝承诺,就像TKrugg已经提到的那样。

看看这个小plunker。不要使用$ timeout服务,只需进行服务器调用即可。

app.directive('verifyStore', function($timeout, $q, $http) {
    return {
        restrict: 'AE',
        require: 'ngModel',
        link: function(scope, elm, attr, model) { 
            model.$asyncValidators.usernameExists = function(modelValue, viewValue) {
                //here you should access the backend, to check if username exists
                //and return a promise
                return $http.get([yourUrl]).then(function(response) {
                    if (!response.data.validUsername) {
                        return $q.reject(response.data.errorMessage);
                    }
                    return true;
                });
            };
        }
    };
});