Angularjs >1.3 $validator 导致 modelValue 未定义
Angularjs >1.3 $validator causes modelValue to go undefined
我正在使用 $validator
编写自定义表单验证指令。
目前看起来是这样的:
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;
};
}
};
});
它检查它附加的元素的模型的字符数,同时考虑到 link 缩短(因此 ng-minlength
和 ng-maxlength
不起作用) .当不满足要求时,它 returns false。问题是当它 returns false modelValue
变为 undefined
时。我知道此时值应该存储在 $$invalidModelValue
中,但我仍然需要原始模型中的值,因为它正在视图中的其他地方使用。
有没有办法阻止 Angular 移动它并制作原始模型 undefined
?我知道这个问题可以在表单控制器中解决,但我认为这不是正确的方法,因为我想使用表单状态而不是一些外部变量来禁用表单提交按钮。在使用 Angular 表单验证时是否有其他方法可以解决此问题?
从 Angular v. 1.3 开始,当 $validate()
returns false, the value of ng-model
is set to undefined (docs here)
要防止此行为,请将 ngModelOptions
的 allowInvalid
属性 设置为 true,如下所示:
ng-model-options="{allowInvalid: true}"
我正在使用 $validator
编写自定义表单验证指令。
目前看起来是这样的:
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;
};
}
};
});
它检查它附加的元素的模型的字符数,同时考虑到 link 缩短(因此 ng-minlength
和 ng-maxlength
不起作用) .当不满足要求时,它 returns false。问题是当它 returns false modelValue
变为 undefined
时。我知道此时值应该存储在 $$invalidModelValue
中,但我仍然需要原始模型中的值,因为它正在视图中的其他地方使用。
有没有办法阻止 Angular 移动它并制作原始模型 undefined
?我知道这个问题可以在表单控制器中解决,但我认为这不是正确的方法,因为我想使用表单状态而不是一些外部变量来禁用表单提交按钮。在使用 Angular 表单验证时是否有其他方法可以解决此问题?
从 Angular v. 1.3 开始,当 $validate()
returns false, the value of ng-model
is set to undefined (docs here)
要防止此行为,请将 ngModelOptions
的 allowInvalid
属性 设置为 true,如下所示:
ng-model-options="{allowInvalid: true}"