本文介绍了Angularjs >1.3 $validator 导致 modelValue 未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 $validator 编写自定义表单验证指令.

I am using $validator to write a custom form validation directive.

目前看起来像这样:

module.directive('tweetLength', function(URLDetector) {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, element, attrs, ctrl) {
      var allowedCharacters;
      allowedCharacters = parseInt(attrs.tweetLength);

      ctrl.$validators.tweetLength = function(modelValue, viewValue) {
        var result;
        return result = URLDetector.urlAdjustedCharacterCount(modelValue) <= allowedCharacters;
      };
    }
  };
});

它检查它所附加的元素模型的字符数,同时考虑链接缩短(所以 ng-minlengthng-maxlength 不要不工作).不满足要求时返回false.问题是当它返回 false 时 modelValue 变为 undefined.我知道此时该值应该存储在 $$invalidModelValue 中,但我仍然需要原始模型中的值,因为它在视图中的其他地方使用.

It checks the model of the element it is attached to for the number of characters, whilst taking into account link shortening (so ng-minlength and ng-maxlength don't work). It returns false when the requirements aren't met. The problem is that when it returns false modelValue goes undefined. I know at this point the value is meant to be stored in $$invalidModelValue, but I still need the value in the original model since it is being used elsewhere in the view.

有没有办法阻止 Angular 移动它并使原始模型 undefined?我知道这个问题可以在表单控制器中解决,但我认为这不是正确的方法,因为我想使用表单状态而不是一些外部变量来禁用表单提交按钮.在使用 Angular 表单验证时,是否有其他方法可以解决此问题?

Is there a way to stop Angular from moving it and making the original model undefined? I know this problem could be solved in the form controller, but I don't think that is the correct way to do it since I want to disable the form submission button using the form state and not some external variable. Is there an alternate way to approach this problem whilst using Angular form validation?

推荐答案

从 Angular v. 1.3 开始,当 $validate() 返回 false,ng-model 的值设置为 undefined (docs 这里)

Beginning in Angular v. 1.3, when $validate() returns false, the value of ng-model is set to undefined (docs here)

为了防止这种行为,设置 allowInvalid 属性>ngModelOptions 设置为 true,如下所示:

To prevent this behavior, set allowInvalid property of ngModelOptions to true, like so:

ng-model-options="{allowInvalid: true}"

这篇关于Angularjs &gt;1.3 $validator 导致 modelValue 未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 11:20