如何在输入字段中添加异步验证器?

时间:2015-10-16 10:04:04

标签: angularjs

在文档中显示了这个:

ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
  var value = modelValue || viewValue;

  // Lookup user by username
  return $http.get('/api/users/' + value).
     then(function resolved() {
       //username exists, this means validation fails
       return $q.reject('exists');
     }, function rejected() {
       //username does not exist, therefore this validation passes
       return true;
     });
};

但是如何将其与输入字段连接?它没有举例说明这一点。

1 个答案:

答案 0 :(得分:0)

您可以在指令link函数中应用验证程序。该指令必须要求ngModel,然后您将该指令作为属性应用于输入标记。在你的情况下,这可能看起来像这样:

angular.directive('isUniqueName', function () {
  return {
    require: 'ngModel',
    link: function ($scope, $elem, $attrs, ngModel) {
      ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
        var value = modelValue || viewValue;

        // Lookup user by username
        return $http.get('/api/users/' + value).
          then(function resolved() {
            //username exists, this means validation fails
            return $q.reject('exists');
          }, function rejected() {
            //username does not exist, therefore this validation passes
            return true;
          })
      }
    }
  }
})

然后在您的HTML代码中:

<input type='text' name='username' ng-model='username' is-unique-name />