【问题标题】:Unable to use ng-minlength for input with custom directive in Angular无法使用 ng-minlength 在 Angular 中使用自定义指令进行输入
【发布时间】:2015-09-14 06:58:12
【问题描述】:

我基于此gist 制定了电话号码格式指令。一切通常都很好。但是,如果我添加 ng-minlength 或 ng-maxlength 验证要求,则输入根本不会接受任何输入。

.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>

【问题讨论】:

标签: angularjs angular-directive


【解决方案1】:

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

在这种情况下,在遇到ng-minlength 之前,您不会看到您的观察者被解雇。

顺便说一句,您可能需要考虑在属性级指令(您的指令是元素指令)上使用ngModelController,作为一种更“角度”的方式来维护视图值与其基础模型值之间的差异。您当前正在寻找 inputValue 更新的观察者内部更新 inputValue,这可能会导致意外行为。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-03
    • 1970-01-01
    • 2019-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-25
    相关资源
    最近更新 更多