如何访问动态创建的FormController?

时间:2017-09-26 15:20:08

标签: javascript angularjs

我有一系列物品。每个项目都会使用ng-repeatng-form动态地与表单相关联。

<div ng-repeat="person in people" ng-form="person.$form">
    ...
</div>

然后我有可能创建新项目。但是当我这样做时,我希望他们的新形式能够

<button type="button" ng-click="addPerson()">ADD NEW ONE...</button>

在控制器中:

$scope.addPerson = function() {
  var p = {
    name: 'Charles',
    color: 'green'
  };
  $scope.people.push(p);

  p.$form.$setDirty(); // <----- THIS WON'T WORK
};

如上述评论所述,这不会奏效。它尝试在创建 FormController 之前执行指令。

到目前为止,我无法找到任何解决方案,也没有完全相关的回答问题。

Here是这个例子中的一个Plunker,富含一些按钮和标签,可用于处理脏和原始状态。

1 个答案:

答案 0 :(得分:2)

创建custom directive以初始化表单:

app.directive("initForm", function() {
  return {
    link: postLink,
    require: 'form'
  }
  function postLink(scope,elem,attrs,form) {
    form.$setDirty();
  }
})

并在HTML中使用它:

<div ng-repeat="person in people" init-form ng-form="person.$form">
    ...
</div>

The DEMO

&#13;
&#13;
angular.module('app', [])

.controller('MainCtrl', function($scope) {
  
  $scope.people = [
    {name: 'Alice',
     color: 'pink'
    },
    {name: 'Bob',
     color: 'blue'
    }
  ];
  
  $scope.addPerson = function() {
    var p = {
      name: 'Charles',
      color: 'green'
    };
    $scope.people.push(p);
    
    //p.$form.$setDirty();
  };
  
})

.directive("initForm", function() {
  return {
    link: postLink,
    require: 'form'
  }
  function postLink(scope,elem,attrs,form) {
    form.$setDirty();
  }
})
&#13;
.ng-pristine {
  background-color: #E0F8F7;
}

.ng-dirty {
  background-color: #F5A9BC;
}

.bigform.ng-pristine {
  background-color: #5882FA;
}

.bigform.ng-dirty {
  background-color: #FF0040;
}

.bigform {
  padding: 20px;
}
&#13;
<script src="//unpkg.com/angular/angular.js"></script>
  <body ng-app="app" ng-controller="MainCtrl">
    <div ng-form="mainForm" class="bigform">
      <div ng-repeat="person in people" 
           init-form
           ng-form="person.$form">
          <p>{{personIndex}}</p>
          <input type="text" ng-model="person.name" />
          <input type="text" ng-model="person.color" />
          <button type="button" ng-click="person.$form.$setPristine()">RE-PRISTINATE</button>
          <label>form is <span ng-show="person.$form.$dirty">dirty</span><span ng-show="person.$form.$pristine">pristine</span></label>
        <br />
      </div>
      <br />
      <br />
      <button type="button" ng-click="mainForm.$setPristine()">RELOAD</button>
    </div>
    <br />
    <br />
    <button type="button" ng-click="addPerson()">ADD NEW ONE...</button>
  </body>
&#13;
&#13;
&#13;