富贵资源网 Design By www.hznty.com
最近在学习angular,那么今天也算个学习笔记吧!
html
<div class="form-group" ng-class="{'has-error': myForm.myName.$touched && myForm.myName.$invalid}"> <label class="col-xs-2 control-label">name</label> <div class="col-xs-6"> <input type="text" class="form-control" name="myName" ng-model="formData.username" placeholder="2-10个中英文字符,aaa会重名,必填" name-check minlength="2" maxlength="10" required> </div> <div class="col-xs-4 form-control-static text-danger" ng-messages="myForm.myName.$error" ng-messages-include="demos/form/error.html" ng-show="myForm.myName.$touched"> </div> </div>
ng-messages="myForm.myName.$error" 给出错误类型(required, char, exist, minlength)
error.html
<span ng-message="required">必填</span> <span ng-message="char">非法字符</span> <span ng-message="exist">名称已存在</span> <span ng-message="minlength">太短了</span>
directive name-check 利用ngModel 的$validators,& $asyncValidators 添加自定义验证
app.directive('nameCheck', nameCheck); nameCheck.$inject = ['HttpService', '$q']; function nameCheck(HttpService, $q){ var NAME_REG = /^[a-zA-Z\u4e00-\u9fa5]+$/; return { restrict: 'A', require: 'ngModel', link:function($scope,element,attrs,ctrl){ ctrl.$validators.char = function(modelValue, viewValue) { var value = modelValue || viewValue; if(!NAME_REG.test(value)){ return false; } return true; }; ctrl.$asyncValidators.exist = function(modelValue, viewValue){ var value = modelValue || viewValue; var deferred = $q.defer(); HttpService.get('api/users/' + value).then(function(res) { if(res.isExist){ deferred.reject(false); } deferred.resolve(true); }) return deferred.promise; } } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
富贵资源网 Design By www.hznty.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
富贵资源网 Design By www.hznty.com
暂无评论...