angularjs:使用ngModel的更好方法。$ asynValidators

时间:2015-03-03 02:30:10

标签: html angularjs-directive angularjs-ng-model

我只是想问一下是否有更好的方法来改进我的用户验证码。

directive.js

angular.module('installApp')
.directive('usernameValidator', function ($q, $timeout, $http) {
   return {
     require: 'ngModel',
       link: function(scope, element, attrs, ngModel) {

          ngModel.$asyncValidators.username = function(modelValue, viewValue) {
            return $http.post('../api/v1/checkUsers', {user: {'username':viewValue}}).then(
              function(response){
                scope.checkUsers = response.data;
                  var deferred = $q.defer();
                    $timeout(function() {
                      if(scope.checkUsers['status'] == 404){
                        deferred.reject();
                      }else{
                        deferred.resolve();
                      }
                    }, 2000);
                   return deferred.promise;
               }); 
             };
          }
       }
   });

accounts.html

  <form name="myForm" ng-submit="submit()">
    <div>
      <label>Username: <input type="text" ng-model="signup.username" name="username" required username-validator>
      </label>
          <div ng-if="myForm.username.$dirty">
            <div ng-messages="myForm.username.$error" class="validation-error">
            <div ng-message="required">Username required</div>
            <div ng-message="username">Username already in use</div>
    </div>
          <div ng-messages="myForm.username.$pending" class="validation-pending">
          <div ng-message="username">Checking username availability...   </div>
          </div>
        </div>
     </div>
     <div>
      <label>Password: <input type="password" ng-model="signup.password" name="password" required></label>
        <div ng-messages="myForm.password.$error" ng-if="myForm.password.$dirty" class="validation-error">
         <div ng-message="required">Password required</div>
        </div>
     </div>
        <button type="submit" ng-disabled="myForm.$invalid || myForm.$pending">Submit</button>
        </form>

上面的代码完全正常,但我心里有一个疑问,我怎样才能以更好的方式改进它。我见过很多例子,我注意到他们主要没有使用if / else条件。请帮忙

1 个答案:

答案 0 :(得分:1)

您可以做的一件事是尝试使您的指令可重用。 我在互联网上找到的一个很好的例子来自Year of moo

angular
.module('yourmodule')
.directive('recordAvailabilityValidator',
  ['$http', function($http) {

  return {
    require : 'ngModel',
    link : function(scope, element, attrs, ngModel) {
      var apiUrl = attrs.recordAvailabilityValidator;

      function setAsLoading(bool) {
        ngModel.$setValidity('recordLoading', !bool); 
      }

      function setAsAvailable(bool) {
        ngModel.$setValidity('recordAvailable', bool); 
      }

      ngModel.$parsers.push(function(value) {
        if(!value || value.length == 0) return;

        setAsLoading(true);
        setAsAvailable(false);

        $http.get(apiUrl, { v : value })
          .success(function() {
            setAsLoading(false);
            setAsAvailable(true);
          })
          .error(function() {
            setAsLoading(false);
            setAsAvailable(false);
          });

        return value;
      })
    }
  }
}]);