angularjs: custom directive to check if a username exists

后端 未结 1 957
说谎
说谎 2020-12-01 19:29

I have my registration form with textbox username. I want to do is when the user enter the username, the custom directive will check if the entered username is exists in the

相关标签:
1条回答
  • 2020-12-01 20:00

    there is a great tutorial by yearofmoo about $asyncvalidators in angular1.3. it allows you to easily show pending status when the field is being checked by the backend:

    here's a working plnkr

    app.directive('usernameAvailable', function($timeout, $q) {
      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
            //here we're using $q and $timeout to mimic a backend call 
            //that will resolve after 1 sec
    
            var defer = $q.defer();
            $timeout(function(){
              model.$setValidity('usernameExists', false); 
              defer.resolve;
            }, 1000);
            return defer.promise;
          };
        }
      } 
    });
    

    html:

    <form name="myForm">
      <input type="text" 
            name="username"
            ng-model="username" 
            username-available 
            required
            ng-model-options="{ updateOn: 'blur' }">
      <div ng-if="myForm.$pending.usernameExists">checking....</div>
      <div ng-if="myForm.$error.usernameExists">username exists already</div>
    </form>
    

    note the use of ng-model-options, another cool feature of 1.3


    edit

    here's a plnkr that shows how to use $http in the directive. note that it is only requesting another .json file, that contains a true/false value. and the directive will set validity on the ng-model accordingly.

    0 讨论(0)
提交回复
热议问题