无法使用 ng-minlength 在 Angular 中使用自定义指令进行输入 [英] Unable to use ng-minlength for input with custom directive in Angular

查看:17
本文介绍了无法使用 ng-minlength 在 Angular 中使用自定义指令进行输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我根据此要点制定了电话号码格式指令.一切都很好.但是如果我添加 ng-minlength 或 ng-maxlength 验证要求,输入将根本不接受任何输入.

I've based a phone number formatting directive on this gist. Everything generally works great. But if I add a ng-minlength or ng-maxlength validation requirement, the input won't accept any input at all.

.directive('phonenumberDirective', ['$filter', function($filter) {

    function link(scope, element, attributes) {

    scope.inputValue = scope.phonenumberModel;

    scope.$watch('inputValue', function(value, oldValue) {

      value = String(value);
      var number = value.replace(/[^0-9]+/g, '');
      scope.phonenumberModel = number;
      scope.inputValue = $filter('phonenumber')(number);
    });
   }

  return {
    link: link,
    restrict: 'E',
    scope: {
      phonenumberPlaceholder: '=placeholder',
      phonenumberModel: '=model'},
      template: '<input ng-model="inputValue" type="tel" id="phone" name="phone" ng-minlength="7" class="phonenumber form-control"  placeholder="{{phonenumberPlaceholder}}" required /> '
    }
}]);

HTML:

<label class="control-label" for="phone">Phone</label>
<phonenumber-directive placeholder="'(000) 000-0000'" model='contactForm.contact.phone'></phonenumber-directive>

<span ng-show="myForm.phone.$error.required && !myForm.phone.$untouched 
|| myForm.phone.$error.required && !myForm.phone.$untouched 
|| myForm.phone.$error.minlength && !myForm.phone.$untouched" class="help-block">
Enter your phone number</span>

推荐答案

如果我正确理解了您的问题,这种行为是正常的.如果输入未通过验证管道,您的 ng-model 将不会更新.

If I understand your question correctly, this behavior is expected. Your ng-model won't be updated if the input does not pass through the validation pipeline.

在这种情况下,在满足 ng-minlength 之前,您不会看到观察者被解雇.

In this case, you won't see your watcher get fired until ng-minlength is met.

顺便说一句,您可能需要考虑使用 ngModelController一个属性级指令(你的是一个元素指令)作为一种更角度"的方式来维护视图值与其底层模型值之间的差异.您当前正在一个观察者中更新 inputValue,该观察者正在寻找对 inputValue 的更新,这可能会导致意外行为.

As an aside, you may want to consider using ngModelController on an attribute-level directive (yours is an element directive) as a more "Angular" way to maintain differences between the view value and its underlying model value. You are currently updating inputValue inside a watcher that is looking for updates to inputValue, which may lead to unexpected behavior.

这篇关于无法使用 ng-minlength 在 Angular 中使用自定义指令进行输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆