Angularjs ng-repeat创建多个表单

J. *_*son 2 javascript angularjs angularjs-directive

使用ng-repeat我正在创建一堆带有值的表单.对于每个表单,还有一个按钮,用新字段向该特定表单添加行.代码如下

HTML:

<div ng-repeat="cont in contacts">
    <form ng-submit="newContact()">
        <input type="text" class="xdTextBox" ng-model="cont.ac"/>
        <input type="text" class="xdTextBox" ng-model="cont.cat"/>
        <input type="text" class="xdTextBox" ng-model="cont.loc"/>
        <button type="submit">Submit</button>
        <a href ng-click="addFields()">Add</a>
    </form>
</div>
Run Code Online (Sandbox Code Playgroud)

使用Javascript:

$scope.contacts = [{ ac: '', auth: '', autname: ''}];
$scope.tasks = [];
$scope.addFields = function () {
    $scope.contacts.push({ ac: '', auth: '', autname: '' });
    console.log($scope.contacts);
}
Run Code Online (Sandbox Code Playgroud)

它正在创建所有表单并添加行但是有两个问题:

  1. 当我添加到新的字段行时,它实际上将行添加到ng-repeat创建的所有表单中.
  2. 当我键入字段或插入字段时,它会将文本复制到所有子表单.

请让我知道如何修复它,以便当按下添加按钮时,只创建该特定形式的行,当我在新推送的字段的字段中输入文本时,它只将它绑定到特定的一个而不是所有创建的那些.谢谢

Ila*_*mer 7

也许我没有理解正确的问题,但我认为你需要的是一种具有多种形式的多重联系的模型.

这是一个吸烟者:http://plnkr.co/edit/fETiSYVW7Y5C1yTCwizd?p =preview

所以你需要嵌套的中继器:

<form name="{{form.name}}"
      ng-repeat="form in forms">

  <h2>{{form.name}}</h2>
  <div ng-repeat="cont in form.contacts">
          <input type="text" class="xdTextBox" ng-model="cont.ac"/>
          <input type="text" class="xdTextBox" ng-model="cont.cat"/>
          <input type="text" class="xdTextBox" ng-model="cont.loc"/>

  </div>
  <button ng-click="submit(form)">Submit</button>
  <button ng-click="addFields(form)">Add</button>
  <hr>
</form>
Run Code Online (Sandbox Code Playgroud)

模型看起来像这样:

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

    $scope.forms = [{
      name: "form1",
      contacts:[{ ac: '', auth: '', autname: ''}]
    },{
      name: "form2",
      contacts:[{ ac: '', auth: '', autname: ''}]
    },{
      name: "form3",
      contacts:[{ ac: '', auth: '', autname: ''}]
    }];

    $scope.addFields = function (form) {        
        form.contacts.push({ ac: '', auth: '', autname: '' });
    };

    $scope.submit = function(form){
      console.log(form.contacts);
    };
});
Run Code Online (Sandbox Code Playgroud)