我想在angularjs中复制模板。就像我点击添加按钮时添加新表单,当我点击删除按钮时删除表单。当我提交按钮时,它会将数据发送到后端,但它会给出错误
TypeError: Cannot read property 'field1' of undefined
,为什么无法获取$scope.field.field1
值。
请参阅demo,它无效
HTML
<div ng-app="myApp" ng-controller="myCtrl">
<div class="col-md-12" style="bottom:10px" >
<div class="form-group" ng-repeat="field in fields">
<div class="col-md-12">
<div class="col-md-4">
<label class="col-md-12 control-label">Field1</label>
<div class="col-md-12">
<input data-ng-model='field.field1' class="chosen-select input-md form-control sme-input-box"/>
</div>
</div>
<div class="col-md-4">
<label class="col-md-12 control-label">Field2</label>
<div class="col-md-12">
<input ng-model='field.field2' class="chosen-select input-md form-control sme-input-box"/>
</div>
</div>
</div>
<div class="col-md-12">
<div class="col-md-3">
<a class="btn btn-success" ng-click="removeTemplate($index)">Remove</a>
</div>
<div class="col-md-3">
<a class="btn btn-success" ng-click="updateOrder()">Submit</a>
</div>
</div>
</div>
<div class="col-md-3" style="top:5px">
<a class="btn btn-success" ng-click="cloneTemplate()">Add</a>
</div>
</div>
</div>
Angularjs
$scope.fields=[
{
"field1": "",
"field2": "",
}
]
// update and get invoice details
$scope.cloneTemplate=function(){
var clone_template={ "field1": "", "field2": ""};
$scope.fields.push(clone_template);
}
$scope.removeTemplate= function(templateIndex){
$scope.fields.splice(templateIndex,1);
}
$scope.updateOrder=function(){
var updateOrder={
"field1":$scope.field.field1,
"field2":$scope.field.field2,
}
$http.post(config.server, updateOrder)
.success(function(response, status){
console.log(response);
})
.error(function(response, status){
console.log(response);
})
}
答案 0 :(得分:1)
ng-repeat
中的变量名称错误,应该是list1
而不是`fields。
<强>标记强>
<div class="form-group" ng-repeat="field in list1">
您可以将范围变量属性重命名为$scope.fields
而不是$scope.list1
修改强>
在提交方法上,您应该将整个字段对象传递给updateOrder
方法,并直接将该对象传递给$http
调用。
另外,您需要在控制器功能上添加缺少的$ http依赖项。
<强>标记强>
<a class="btn btn-success" ng-click="updateOrder(field)">Submit</a>
<强>代码强>
$scope.updateOrder = function(field) {
//pass the field object as is, because it will have field1 & field2
var config = { server: '/url'}//should be something
$http.post(config.server, field)
.success(function(response, status) {
console.log(response);
})
.error(function(response, status) {
console.log(response);
})
}
答案 1 :(得分:1)
没有$scope.field
,请阅读Understanding Scopes。
您可以在视图
中的updateOrder函数中传递$ index<a class="btn btn-success" ng-click="updateOrder($index)">Submit</a>
并像这样使用
$scope.updateOrder=function(i){
var updateOrder = {
"field1":$scope.fields[i].field1,
"field2":$scope.fields[i].field2,
};
.....
};