我有一个数组,我从中获取一些值来创建表单的某些字段。创建它之后,我需要将我自动填充的新数组发送到服务器。问题是我需要从第一个发送相同的数组,当然还有新的值。我在这里创建了一个例子:
https://jsfiddle.net/vuqcopm7/2/
这里有一些代码:
HTML:
<div ng-app='myApp' ng-controller='mycontroller'>
<div data-ng-repeat="item in myNewArray.newArray track by $index">
<div ng-if="item.attrType == 'text'">
<input id="form-f{{$index}}" type="text" placeholder="{{item.attrname}}" data-ng-model="item.attrValue"/>
</div>
</div>
<div data-ng-repeat="object in getItems.data">
<div data-ng-repeat="att in object.objects">
<ul ng-repeat="data in att.attributes">
<li>
<a ng-click="pushItems(att.name, data)">{{data.attrname}}</a>
</li>
</ul>
</div>
</div>
<p>{{showNewJson()}}</p>
</div>
JS:
var myApp = angular.module('myApp',[]);
myApp.controller("mycontroller", ["$scope", "$http",
function($scope, $http){
$scope.getItems = {
"data": [
{
"label": "first",
"objects": [
{
"name": "firstObj",
"attributes": [
{
"attrname": "asd1",
"attrValue": "",
"attrType":"text"
},
{
"attrname": "asd2",
"attrValue": "",
"attrType":"text"
}
]
}
],
"key": "bolla"
},
{
"label": "second",
"objects": [
{
"name": "secondObj",
"attributes": [
{
"attrname": "asd",
"attrValue": "",
"attrType":"text"
},
{
"attrname": "asd3",
"attrValue": "",
"attrType":"text"
}
]
}
],
"key": "2"
}
]
};
$scope.filterSelected = $scope.getItems.data[0].objects;
$scope.myNewArray = {
newArray: [
]
}
$scope.pushItems = function pushItems(attribute, items) {
$scope.myNewArray.newArray.push(angular.copy(attribute), angular.copy(items));
console.log($scope.myNewArray);
}
$scope.showNewJson = function() {
return $scope.myNewArray;
}
}]);
ps:我正在使用angularjs
编辑:我更新了小提琴:https://jsfiddle.net/vuqcopm7/3/
这应该是正确的json我会:
{
"objects": [
{
"name": "firstObj",
"attributes": [
{
"attrname": "asd1",
"attrValue": "asdas",
"attrType": "text"
},
{
"attrname": "asd2",
"attrValue": "sadsa",
"attrType": "text"
},
{
"name": "secondObj",
"attributes": [
{
"attrname": "asd3",
"attrValue": "tttt",
"attrType": "text"
},
{
"attrname": "asd4",
"attrValue": "qqq",
"attrType": "text"
}
]
}
]
}
]
}
答案 0 :(得分:1)
这是我的最终答案 - https://jsfiddle.net/vuqcopm7/8/
$scope.myNewArray = {
objects: [
]
}
$scope.createjson = function(attribute, items) {
var obj = {};
obj.name = angular.copy(attribute);
obj.attributes = [];
obj.attributes.push(angular.copy(items));
return obj;
}
$scope.checkIfAttributeExists = function(attribute) {
for(var i=0; i<$scope.myNewArray.objects.length; i++) {
if($scope.myNewArray.objects[i]["name"] == attribute) {
return i;
}
}
return -1;
}
$scope.pushItems = function pushItems(attribute, items) {
var index = $scope.checkIfAttributeExists(attribute);
if(index == -1) {
var obj = $scope.createjson(attribute, items);
$scope.myNewArray.objects.push(obj);
}
else {
$scope.myNewArray.objects[index].attributes.push(items);
}
//console.log($scope.myNewArray);
}
$scope.showNewJson = function() {
return $scope.myNewArray;
}