Angularjs: custom directive to check for username

I have my registration form with the username in the text box. I want to do when the user enters the username, the user directive checks if the entered username exists in the database.

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); }); }); }); } } }); 

If it exists, my div class = "invalid" will be displayed in html form labeled "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> 

But right now they are not working :-(, am I right? Please advise or suggest me what I should do. Thanks in advance.

+6
source share
1 answer

There is a great tutorial from yearofmoo about $ asyncvalidators in corner1.3. it makes it easy to display pending status when a field is checked by the backend:

plnkr works here

 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> 

note the use of ng-model-options , another interesting feature 1.3


change

here plnkr where it shows how to use $ http in the directive. note that it only requests one .json file containing the value true / false. and the directive will accordingly establish the correctness for the ng-model.

+16
source

Source: https://habr.com/ru/post/982982/


All Articles