Angularjs重复表单字段

时间:2015-09-11 13:11:50

标签: angularjs forms

我为培训网站建了一个购物车。人们可以为每个培训课程购买一些“座位”。我需要添加的是一个表格,要求每个座位(与会者)的姓名和电子邮件。因此,如果有人购买3个席位,那么我需要为每个与会者生成表单字段。

我假设下面的代码中有一些东西在解决这个问题中起了作用,但是我在Angular中不够熟练,无法解决这个问题。

ng-repeat="i in quantity track by $index"

3 个答案:

答案 0 :(得分:1)

首先,获取表格中的席位数(如果表格在另一个角度控制器中,则通过事件或共享服务发送席位号)所以,在表格控制器中说$ scope.nbrSeats(初始值= 0)

其次,使用ng-repeat:

<form ng-repeat="i in nbrSeats">...</form>

答案 1 :(得分:1)

看看这个codepen 它工作正常:))

var app = angular.module('myapp',[]);
app.controller('ctrlParent',function($scope){
    $scope.myNumber=1;
      $scope.range = function(count){
        var output = []; 
        for (var i = 0; i < count; i++) { 
            output.push(i) 
        }; 
        return output;
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp">
    <div ng-controller="ctrlParent">

      
            <input ng-model="myNumber" type="text" placeholder="Quantity"/>

        <form ng-repeat="i in range(myNumber) track by $index">
            <input type="text" placeholder="Name"/>
            <input type="text" placeholder="Name"/>
            <input type="text" placeholder="Name"/>
            <input type="button" value="Ok"/>
        </form>
    </div>
</div>

答案 2 :(得分:1)

以下是您的工作示例:

var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', function($scope) {
  
  $scope.quantity = '1';
  $scope.availableQuantity = '10';
  
  $scope.range = function(num) {
    num = parseInt(num);
    return new Array(num);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp" ng-controller="MyCtrl">
  
  <form name="myForm">
    
    <select ng-model="quantity">
      <option ng-repeat="option in range(availableQuantity) track by $index">{{$index + 1}}</option>
    </select><br/><br/>
    
    <div ng-repeat="customer in range(quantity) track by $index">
      Customer {{$index + 1}} name: <input type="text" ng-model="customer_$index"><br/>
    </div><br/><br/>
    
    <button type="submit">Purchase</button>
    
  </form>
  
</div>