【问题标题】:AngularJS - exclude field from form validation / dirtyAngularJS - 从表单验证/脏中排除字段
【发布时间】:2023-03-15 14:27:01
【问题描述】:

我在ng-form 内有一个checkboxHTML5 form 敲击,我想排除它,这样它就不会改变我的表单$state$pristine$dirty)。

我尝试过使用 ignoreDirty 指令 - Angular 1.2: Is it possible to exclude an input on form dirty checking?

还有一些其他解决方案,在HTML5 form 内没有一个适用于ng-form,一些示例代码:

<form name="mainForm" class="col-xs-10 form-validation" novalidate>
  <ng-form name="innerForm">
    <div>
      <span>check my
        <span ng-if="vm.utils.mode!=='readonly'">
          <input type="checkbox" 
                 ng-model="vm.utils.amalotSecond" 
                 class="secondYearCheckBox">
        </span>
      </span>
    </div>
  </ng-form>
<form>

【问题讨论】:

    标签: javascript angularjs html forms


    【解决方案1】:

    您提供的ignoreDirty 指令可以正常工作,就像在此demo fiddle 中一样。以下代码示例取自 angular-1-2-is-it-possible-to-exclude-an-input-on-form-dirty-checking。还要尽量避免使用不符合 HTML 的嵌套表单。 form 元素不能有元素 form。这将导致问题和错误,例如你现在面对的那个。

    查看

    <div ng-controller="MyCtrl">
      <form name="test">
        Watching dirty: <input ng-model="name"  /><br />
        Ignoring dirty: <select ng-model="gender" ignore-dirty>
          <option>male</option>
          <option>female</option>
        </select><br />
        dirty: {{test.$dirty}}
      </form>
    </div>
    

    AngularJS 应用程序

    var myApp = angular.module('myApp',[]);
    
    myApp.controller('MyCtrl', function ($scope) {
        $scope.name = 'Superhero';
    });
    
    myApp.directive('ignoreDirty', [function() {
        return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, elm, attrs, ctrl) {
          ctrl.$setPristine = function() {};
          ctrl.$pristine = false;
        }
      }
    }]);
    

    【讨论】:

    • 输入在ng-form里面。
    • 是的,它不会改变你的$dirty 状态。
    • 哪种形式?让我试试你的小提琴,它仍然会改变外部形式的状态。
    • 嗯 m8,元素 form 不能有子元素 form。只需将其删除,因为它不符合 HTML。
    猜你喜欢
    • 1970-01-01
    • 2014-02-22
    • 2011-10-17
    • 2015-06-30
    • 2014-06-14
    • 1970-01-01
    • 1970-01-01
    • 2013-07-18
    • 2013-08-30
    相关资源
    最近更新 更多