问题
I am using $validator
to write a custom form validation directive.
Currently it looks like this :
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;
};
}
};
});
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.
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?
回答1:
Beginning in Angular v. 1.3, when $validate() returns false, the value of ng-model
is set to undefined (docs here)
To prevent this behavior, set allowInvalid
property of ngModelOptions to true, like so:
ng-model-options="{allowInvalid: true}"
来源:https://stackoverflow.com/questions/29111328/angularjs-1-3-validator-causes-modelvalue-to-go-undefined