嗨,我正在尝试将下一个对象放在一起
$ scope.passengers = {
成人:[{名字:“ name”,姓氏:“ anothername”},{firstname:“ name”,姓氏:“ anothername”},{firstname:“ name”,姓氏:“ anothername”}]],
子级:[{名字:“ name”,姓氏:“ anothername”},{firstname:“ name”,姓氏:“ anothername”},{firstname:“ name”,姓氏:“ anothername”}]],
extras:“ someValue”};
在我的控制器中,我有以下内容
$scope.passengers = {};
$scope.passengers.adult = [];
$scope.passengers.child = [];
$scope.numberAdult = 10;
$scope.numberChildren = 10;
Y las funciones
//Functions return an array null
$scope.getNumber = function(num) {
num = parseInt(num);
return new Array(num);
};
$scope.savePassengers = function(product_id)
{
//for the moment only print the variable
console.log($scope.passengers)
}
在我的HTML页面中
<form name="passengers-form" ng-submit="savePassengers(product.id)">
<div class="col-lg-12">
<div class="form-horizontal">
<div class="row">
<div class="form-group" ng-repeat="a in getNumber(numberAdult) track by $index">
<label class="col-sm-3 control-label">Adult {{$index + 1 }}</label>
<div class="col-sm-3">
<input required ng-model="passengers.adult[$index].firstname" class="form-control" placeholder="First Name" type="text">
</div>
<div class="col-sm-3">
<input required ng-model="passengers.adult[$index].lastname" class="form-control" placeholder="Last Name" type="text">
</div>
</div>
<div class="form-group" ng-repeat="a in getNumber(numberChildren) track by $index">
<label class="col-sm-3 control-label">Child {{$index + 1 }}</label>
<div class="col-sm-3">
<input required ng-model="passengers.child[$index].firstname" class="form-control" placeholder="First Name" type="text">
</div>
<div class="col-sm-3">
<input required ng-model="passengers.child[$index].lastname" class="form-control" placeholder="Last Name" type="text">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Extras</label>
<div class="col-sm-6">
<textarea name="" ng-model="passengers.extras"class="form-control" id="" cols="30" rows="10"></textarea>
</div>
</div>
<div class="col-xs-9 col-sm-9 col-md-9 col-lg-9">
<div class="form-group buttons pull-right">
<button class="btn btn-primary" id="guardar" type="submit">
<i class="fa fa-save"></i>Add to Cart ->
</button>
</div>
</div>
</div>
</div>
</div>
<div class="clearfix"></div>
</form>
但是,当我打印变量“ passenger”时,控制台显示:
Object {extras: "someValue"}
最佳答案
您的问题是ng-repeat
创建了一个隔离的作用域,因此您的输入字段未反映在正确的作用域中。可以通过正确填写您的extras
字段来进一步验证。
您应该在HTML中更改这些行:
<input required ng-model="$parent.passengers.adult[$index].firstname" class="form-control" placeholder="First Name" type="text">
...
<input required ng-model="$parent.passengers.adult[$index].lastname" class="form-control" placeholder="Last Name" type="text">
并为儿童区域做同样的事情。
关于javascript - 以 Angular 保存对象数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32791700/