Skip nested forms validation with AngularJS

后端 未结 12 2086
失恋的感觉
失恋的感觉 2020-12-23 18:16

How can I skip validation of nested forms with AngularJS? I have to make an outer form valid even when its child form is invalid.

In the example below outer form sh

12条回答
  •  孤城傲影
    2020-12-23 18:23

    I faced the same problem. Inside a larger form I needed to have a subform with several controls that shouldn't touch the state of the parent form.

    Here's my solution: I wrote a directive "null-form" that removes the subform from the parent form and that does not send any state changes its parent.

    angular.module('nullForm',[]).directive('nullForm', [function () {
      return {
        restrict: 'A',
        require: '?form',
        link: function link(scope, element, iAttrs, formController) {
    
          if (! formController) {
            return;
          }
    
          // Remove this form from parent controller
          var parentFormController = element.parent().controller('form');
          parentFormController.$removeControl(formController);
    
          // Replace form controller with a "null-controller"
          var nullFormCtrl = {
            $addControl: angular.noop,
            $removeControl: angular.noop,
            $setValidity: angular.noop,
            $setDirty: angular.noop,
            $setPristine: angular.noop
          };
    
          angular.extend(formController, nullFormCtrl);
        }
      };
    }]);
    

    You can then use it like this:

    Any change or negative validation of "inside" won't take an effect on "parent".

    There's one downside, however, due to this solution: subform will not have any state either nor will its CSS classes like ng-invalid etc. work. To accomplish this you would need to re-implement this functionality from the original form-controller.

提交回复
热议问题