angularjs: 检查用户名是否存在的自定义指令

angularjs: custom directive to check if a username exists

我有带有文本框用户名的注册表。我想做的是当用户输入用户名时,自定义指令将检查输入的用户名是否存在于数据库中。

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>

但是现在,他们不工作:-(,我做的对吗?请给我建议或建议我应该做的事情。提前致谢。

yearofmoo 有一篇很棒的 tutorial 关于 angular1.3 中的 $asyncvalidators。它允许您在后端检查字段时轻松显示待处理状态:

这是一个有效的 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-model 的有效性。