父ngForm基于子表单的脏状态

时间:2016-06-14 23:13:39

标签: angularjs angularjs-ng-form

我在尝试保持父级ngForm状态更新时遇到了一些问题;它应该设置为" Pristine"当所有的孩子都被清理干净并设置为" Pristine"他们自己......但似乎不会自动发生。

我在这里创建了一个插件来更好地解释问题:http://plnkr.co/edit/vCX7ltOb8fgl3fkEpvzy?p=preview

<body ng-controller="MainCtrl">

    <div ng-form="parentForm1" class="parent-form">
      parentForm1.dirty: <b>{{parentForm1.$dirty}}</b>

      <form name="childForm1" class="child-form" novalidate>
        childForm1.dirty: <b>{{childForm1.$dirty}}</b>
        <br/>
        <input type="text" ng-model="field1">
        <br/>
        <button ng-click="reset1()">Clean and setPristine</button>
      </form>

      <form name="childForm2" class="child-form" novalidate>
        childForm2.dirty: <b>{{childForm2.$dirty}}</b>
        <br/>
        <input type="text" ng-model="field2">
        <br/>
        <button ng-click="reset2()">Clean and setPristine</button>
      </form>

    </div>

  </body>

我哪里错了?我找到了使用外部模块的解决方案......我想用尽可能少的代码来解决它(也许是一个指令?)。

1 个答案:

答案 0 :(得分:0)

我用&#34; angular-input-modified&#34;找到了我自己的答案。这是更新的插件:http://plnkr.co/edit/vCX7ltOb8fgl3fkEpvzy?p=preview

HTML:

<!DOCTYPE html>
<html ng-app="test">

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
  <script src="//rawgit.com/betsol/angular-input-modified/master/dist/angular-input-modified.js"></script>
  <script src="script.js"></script>
  <link rel="stylesheet" href="style.css" />
</head>

<body ng-controller="MainCtrl">

  <div ng-form="parentForm1" class="parent-form">
    parentForm1.dirty: <b>{{parentForm1.$dirty}}</b>
    <br/>
    parentForm1.modified: <b>{{parentForm1.modified}}</b>

    <form name="childForm1" class="child-form" novalidate>
      childForm1.dirty: <b>{{childForm1.$dirty}}</b>
      <br/>
      <input type="text" ng-model="field1">
      <br/>
      <button ng-click="reset1()">Clean and setPristine</button>
    </form>

    <form name="childForm2" class="child-form" novalidate>
      childForm2.dirty: <b>{{childForm2.$dirty}}</b>
      <br/>
      <input type="text" ng-model="field2">
      <br/>
      <button ng-click="reset2()">Clean and setPristine</button>
    </form>

  </div>

  <form name="exChildForm1" class="child-form" novalidate>
    exChildForm1.dirty: <b>{{exChildForm1.$dirty}}</b>
    <br/>
    <input type="text" ng-model="exfield1">
    <br/>
    <button ng-click="exreset1()">Clean and setPristine</button>
  </form>

</body>

</html>

JS:

var app = angular.module('test', ['ngInputModified']);

app.controller('MainCtrl', function($scope) {

  $scope.reset1 = function() {
    $scope.field1 = null;
    $scope.childForm1.$setPristine();
  }

  $scope.reset2 = function() {
    $scope.field2 = null;
    $scope.childForm2.$setPristine();
  }

  $scope.exreset1 = function() {
    $scope.exfield1 = null;
    $scope.exChildForm1.$setPristine();
  }

});