大家。使用angularjs 1.2v。我在模型中有一个数组。页面很大,所以我会尽快描述它。
$scope.model={
salary,
position,
user:
[{
name:'',
address:''
}]
}
将项目添加到该数组中的功能:
$scope.submitFunc = function(item){
$model.user.push(item);
}
这是html文件:
<div class="panel panel-success" ng-repeat="item in model.user">
<div class="form-group">
<label>NameLabel</label>
<input ng-model="item.name" type = text />
</div>
<div class="form-group">
<label>addressLabel</label>
<input ng-model="item.address" type = text />
</div>
<button ng-click="submitFunc(item)">Submit<>
</div>
单击按钮后,我需要模型中的数组看起来像这样:
$scope.model={
'salary': 'some value',
'position': 'some value',
'user':[{name: 'value', address:'value2'},
{name: 'value3', address:'value4'},
... ]
}
如何构建提交功能更正它以添加新值而不仅仅是重写它们?此目的是用户能够随机填写的一种形式。按钮点击数据应该转到数组,字段应该被清除......谢谢!
答案 0 :(得分:1)
您需要复制该对象。您正在传递参考:
angular.copy(source);
https://docs.angularjs.org/api/ng/function/angular.copy
$scope.submitFunc = function(item){
$model.user.push(angular.copy(item));
}
答案 1 :(得分:0)
试试这个会起作用:
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl',function ($scope) {
$scope.model={
salary:'',
position:'',
user:
[{
name:'',
address:''
}]
}
$scope.submitFunc = function(item){
$scope.model.user.push(angular.copy(item));
$scope.model.user.pop(angular.copy(item));
$scope.model.user.push({
name:'',
address:''
});
console.log($scope.model);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<div class="panel panel-success" ng-repeat="item in model.user">
<div class="form-group">
<label>NameLabel</label>
<input ng-model="item.name" type = text />
</div>
<div class="form-group">
<label>addressLabel</label>
<input ng-model="item.address" type = text />
</div>
<button ng-click="submitFunc(item)">Submit</button>
</div>
</div>