zoukankan      html  css  js  c++  java
  • 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);
    }());
  • 相关阅读:
    等保测评(一)
    一个基于RNN的实体抽取工具
    如何画UML类图
    mysql存储过程整理
    记一次mysql事务未提交导致锁未释放的问题
    开启·元宇宙·区块链金融
    Nacos启动报错:[db-load-error]load jdbc.properties error
    使用Bazel编译TypeScript
    Win10上Docker无法正常启动 出现install WSL2 kernel update的情况
    VSCode调试PHP环境配置 phpstudy vscode xdebug调试
  • 原文地址:https://www.cnblogs.com/darrenji/p/5158145.html
Copyright © 2011-2022 走看看