AngularJS> 1.3 $ validator导致modelValue变为未定义 [英] Angularjs >1.3 $validator causes modelValue to go undefined
问题描述
我正在使用$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-minlength
和ng-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开始,当此处)
Beginning in Angular v. 1.3, when $validate()
returns false, the value of ng-model
is set to undefined (docs here)
为防止此行为,请设置 ngModelOptions
的allowInvalid
属性变为真实,就像这样:
To prevent this behavior, set allowInvalid
property of ngModelOptions
to true, like so:
ng-model-options="{allowInvalid: true}"
这篇关于AngularJS> 1.3 $ validator导致modelValue变为未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!