How do I prevent AngularJS from unbinding a form input's value from its model when it's invalid?

后端 未结 3 1631
[愿得一人]
[愿得一人] 2021-01-13 09:56

I\'m building a form with AngularJS, and I noticed some behavior I don\'t understand.

When I assign ng-minlength=5 as an input attribute, AngularJS unbi

3条回答
  •  逝去的感伤
    2021-01-13 10:16

    You could also write a custom validator directive to restore the $viewValue for you like this:

    .directive('myParser', function () {
      return {
        restrict: 'A',
        require: 'ngModel',
        priority: 1, // force the postLink below to run after other directives
        link: function (scope, element, attrs, modelCtrl) {
          modelCtrl.$parsers.push(function (viewValue) {
            return (viewValue === undefined) ? modelCtrl.$viewValue : viewValue;
          });
        }
      }
    });
    

    and use it like this:

    
    

    Example plunker: http://plnkr.co/edit/LbhF865FS8Zq5bQnpxnz?p=preview

提交回复
热议问题