我有这个代码用于动态添加输入字段 HTML
<div ng-app="timeTable" ng-controller="addCoursesCtrl">
<button class="btn btn-primary" ng-click="addNewCourse()">Add New Course</button><br/><br/>
<fieldset ng-repeat="choice in choices">
<div class="row">
<div class="col-md-6">
<select class="form-control">
<option>Lab</option>
<option>Theory</option>
</select>
</div>
<div class="col-md-6">
<input type="text" placeholder="Enter Course Name" name="" class="form-control" />
</div>
</div>
<br/>
</fieldset>
<h2>
{{choice}}
</h2>
</div>
js
timeTable.controller("addCoursesCtrl", function ($scope) {
$scope.choices = [{id:'choice1'},{id:'choice2'}];
$scope.addNewCourse = function () {
var newITemNo = $scope.choices.length + 1;
$scope.choices.push({ 'id': 'choice' + newITemNo });
};
});
每次你点击addnewCourse按钮时,在我的控制器中,它会为数组添加新的选择,而在我的html中我使用ng-repeat添加需要的输入,但我的问题是如何获取数据并将数组作为对象放入我的prefrerd对象是数组
[{ “课程”:值.., “类型”:值....},{ “场”:值.., “类型”:值....}]
并以此形状将其发送到服务器,以便这样做的首选方式,输入feild的课程值以及select中的类型值。
答案 0 :(得分:0)
您要发送到服务器的数据可以使用ng-model直接绑定到视图。
定义服务器所需的数据(最终,在服务中执行此操作):
$scope.choices = [{id:'choice1', course:'', type:''},{id:'choice2', course:'', type:''}];
在视图中:
...
<fieldset ng-repeat="choice in choices">
...
<input type="text" placeholder="Enter Course Name" name=""
ng-model="choice.course"
class="form-control" />
...
<select class="form-control" ng-model="choice.type">
<option>Lab</option>
<option>Theory</option>
</select>
...
转换为json以发送到服务器:
var asJson = angular.toJson($scope.choices);
答案 1 :(得分:0)
您只需在选择和输入中添加ngModel
即可。首先,使用空数组创建范围变量:
$scope.formData = [];
然后,在您的标记中,在重复中添加ng-model
并使用$index
变量来跟踪数组:
<fieldset ng-repeat="choice in choices">
<div class="row">
<div class="col-md-6">
<select ng-model="formData[$index].Type" class="form-control">
<option>Lab</option>
<option>Theory</option>
</select>
</div>
<div class="col-md-6">
<input ng-model="formData[$index].Course" type="text" placeholder="Enter Course Name" name="" class="form-control" />
</div>
</div>
<br/>
</fieldset>
这是jsFiddle