AngularJS中巧用ngModel的$asyncValidators属性写一个验证唯一性的Direcitve

有这样的一个需求:添加用户的时候,根据主键判断当前添加用户的email是否已经被使用。

为此,我们需要把主键和email来传递给远程的一个API,让API返回结果,告之当前email是否被使用过。

写一个验证email唯一性的Directive,页面大致如下表现:

<input type="text" name="email" class="form-control"
    data-ng-model="vm.customer.email"
    data-ng-model-options="{updateOn: 'blur', allowInvalid: true}"
    data-my-unique
    data-my-unique-key="{{vm.customer.id}}"
    data-my-unique-property="email"
    data-ng-minlength="3"
    required />
    
<span class="errorMessage" ng-show="editForm.email.$touched && editForm.email.$error.unique">
    Email already in use
</span>    

以上,data-my-unique-key用来接收主键,data-my-unique-property用来接受email这个值。


Directive部分大致如下:

(function(){
    var injectParams = ['$q', 'dataService'];
    var myUniqueDirective = function($q, dataService){
    
        var link = function(scope, element, attrs, ngModel){
            ngModel.$asyncValidators.unique = function(modelValue, viewValue){
                var deferred = $q.defer(),
                    currentValue = modelValue || viewValue,
                    
                    //获取主键
                    key = attrs.myUniqueKey,//my-unqiue-key = "{{customer.id}}"
                    
                    //获取email
                    property=attrs.myUnqiueProperty; //my-unique-property="email"
                
                if(key && property){
                    dataService.checkUniqueValue(key, property, currentValue)
                        .then(function(unique){
                            if(unique){
                                deferred.resolve();
                            } else {
                                deferred.reject();
                            }
                        });
                    return deferred.promise;
                } else {
                    return $q.when(true);
                }
            }
        };
       
        return {
            restrict: 'A',
            require: 'ngModel',
            link: link
        }
    };
    
    myUniqueDirective.$inject = injectParams;
    
    angular.module('customersApp').directive('myUnique', myUniqueDirective);
}());
原文地址:https://www.cnblogs.com/darrenji/p/5158145.html