Unable to use ng-minlength for input with custom d

2019-09-08 06:00发布

问题:

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>

回答1:

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.

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

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.