Validation of invisible and disabled fields in AngularJS

后端 未结 3 815
陌清茗
陌清茗 2020-12-29 09:11

Is there any way to do conditional validation in AngularJS? The problem I am trying to solve is basically a list of radio buttons that enable/disable inputs based on the sel

3条回答
  •  隐瞒了意图╮
    2020-12-29 09:50

    Try this directive:

    .directive('disableChildren', function() {
      return {
        require: '^form',
        restrict: 'A',
        link: function(scope, element, attrs,form) {
          var control;
    
          scope.$watch(function() {
            return scope.$eval(attrs.disableChildren);
          }, function(value) {
            if (!control) {
              control = form[element.find("input").attr("name")];
            }
            if (value === false) {
              form.$addControl(control);
              angular.forEach(control.$error, function(validity, validationToken) {
                form.$setValidity(validationToken, !validity, control);
              });
            } else {
              form.$removeControl(control);
            }
          });
        }
      }
    })
    

    DEMO

    For more information and explanation of how it works. Check out my similar directive for excluding hidden elements from validation:

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

    I think we could somehow combine these directives to create a general directive that could be used everywhere depending on how we evaluate an expression.

提交回复
热议问题