angularjs:用于检查用户名是否存在的自定义指令
发布时间:2020-12-17 08:20:28 所属栏目:安全 来源:网络整理
导读:我的注册表格带有文本框用户名.我想要做的是当用户输入用户名时,custom指令将检查输入的用户名是否存在于数据库中. directives.js angular.module('installApp').directive('pwCheck',function ($http) { return { require: 'ngModel',link: function (scope
我的注册表格带有文本框用户名.我想要做的是当用户输入用户名时,custom指令将检查输入的用户名是否存在于数据库中.
directives.js angular.module('installApp').directive('pwCheck',function ($http) { return { require: 'ngModel',link: function (scope,elem,attrs,ctrl) { elem.on('blur',function (evt) { scope.$apply(function () { $http({ method: 'GET',url: '../api/v1/users',data: { username:elem.val(),dbField:attrs.ngUnique } }).success(function(data,status,headers,config) { ctrl.$setValidity('unique',data.status); }); }); }); } } }); 如果它存在,我的div class =“invalid”将显示在html表单中,标签为“Username already exists”. registration.html <form name = "signupform"> <label>{{label.username}}</label> <input type="text" id = "username" name = "username" ng-model="user.username" class="form-control"></input> <div class="invalid" ng-show="signupform.username.$dirty && signupform.username.$invalid"><span ng-show="signupform.username.$error.unique">Username already exists.</span> </div> </form> 但是现在,他们没有工作:-(我做得对吗?请建议或建议我应该做的事情.提前谢谢.
在angular1.3中有一个关于$asyncvalidator的年份很好的
tutorial.它允许您在后端检查字段时轻松显示挂起状态:
这是plnkr的工作 app.directive('usernameAvailable',function($timeout,$q) { return { restrict: 'AE',require: 'ngModel',link: function(scope,elm,attr,model) { model.$asyncValidators.usernameExists = function() { //here you should access the backend,to check if username exists //and return a promise //here we're using $q and $timeout to mimic a backend call //that will resolve after 1 sec var defer = $q.defer(); $timeout(function(){ model.$setValidity('usernameExists',false); defer.resolve; },1000); return defer.promise; }; } } }); HTML: <form name="myForm"> <input type="text" name="username" ng-model="username" username-available required ng-model-options="{ updateOn: 'blur' }"> <div ng-if="myForm.$pending.usernameExists">checking....</div> <div ng-if="myForm.$error.usernameExists">username exists already</div> </form> 注意使用ng-model-options,1.3的另一个很酷的功能 编辑 这是一个plnkr,显示如何在指令中使用$http.请注意,它只是请求另一个包含true / false值的.json文件.并且该指令将相应地设置ng模型的有效性. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |