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);
    }());
  • 相关阅读:
    新版新概念英语14册(英音+美音)MP3打包下载
    最近学习目标
    本人兼职C#,WinForm ,数据库,MapXtreme, Arcgis Engine 相关的开发
    everything is good on
    人之惰性思考
    css hacks 以及解决办法
    hibernate学习(1)——核心接口
    【原】可关闭,可重播的flash弹出广告代码
    PNG在IE6下透明问题的解决办法
    JSP解压ZIP压缩文件
  • 原文地址:https://www.cnblogs.com/darrenji/p/5158145.html
Copyright © 2011-2022 走看看