Angularjs >1.3 $validator causes modelValue to go undefined

耗尽温柔 提交于 2020-01-15 01:20:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!