AngularJS - 从表单验证/脏检查中排除字段

7
我在HTML5表单中有一个ng-form包裹的复选框,我希望将其排除在外,以便它不会改变我的表单$state($pristine 或者 $dirty)。
我尝试使用ignoreDirty指令 - Angular 1.2: Is it possible to exclude an input on form dirty checking? 和其他一些解决方案,但都无法在HTML5表单内使用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>
1个回答

9
您提供的ignoreDirty指令在此演示代码中可以正常工作。以下代码示例摘自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内。 - Itsik Mauyhas
嗨,伙计,元素 form 不能有子元素 form。只需将其删除,因为它不符合 HTML 规范。 - lin
我同意,像这个问题一样,它可能会引起很多问题,我需要它是因为我需要实现一些业务逻辑。 - Itsik Mauyhas
@ItsikMauyhas,您不需要父表单来检查页面上所有或某些表单是否有效/脏/发送或其他。您还可以使用自定义函数一次性发送所有表单。这样,您就可以避免现在遇到的所有问题。保持简单。 - lin
你说得对,我只是希望有一个更干净的解决方案,而不是使用单一表格。谢谢。 - Itsik Mauyhas
显示剩余8条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接