implementing a directive to exclude a hidden input element from validation ($addControl issue)

后端 未结 2 1797

I\'m creating a directive to exclude a hidden input element from validation: http://plnkr.co/edit/Vnwvq2AT7JpgTnoQwGh9?p=preview

app.directive(\'shownValidat         


        
相关标签:
2条回答
  • 2020-12-19 05:08

    It seems you are hiding the element using ng-show and thus not submitting the input along with the form.

    In this case, we can use ng-if directive in the view in order to remove the element on the fly. This would remove the element and it's validity too.

    0 讨论(0)
  • 2020-12-19 05:16

    If the control is removed angular updates the validity (from the sources):

      form.$removeControl = function(control) {
        if (control.$name && form[control.$name] === control) {
          delete form[control.$name];
        }
        forEach(errors, function(queue, validationToken) {
          form.$setValidity(validationToken, true, control);
        });
    
        arrayRemove(controls, control);
      };
    

    If you add the control angular did not update the validity (from the sources):

      form.$addControl = function(control) {
        // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
        // and not added to the scope.  Now we throw an error.
        assertNotHasOwnProperty(control.$name, 'input');
        controls.push(control);
    
        if (control.$name) {
          form[control.$name] = control;
        }
      };
    

    so we have to do this manually. I guess this way:

    if (value == true){
        form.$addControl(control); 
        angular.forEach(control.$error, function(validity, validationToken) {
           form.$setValidity(validationToken, !validity, control);
        });
       }else{
        form.$removeControl(control);
       }
    }
    
    0 讨论(0)
提交回复
热议问题