When working with an array to populate form fields and send data to a server, it's important to handle updating the array with new values. Below is an example showcasing this process:
Highlighted code snippets:
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',[]);
// Angular controller function
myApp.controller("mycontroller", ["$scope", "$http",
function($scope, $http){
// Initial data structure
$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: [
]
}
// Function to update the array with new values
$scope.pushItems = function pushItems(attribute, items) {
$scope.myNewArray.newArray.push(angular.copy(attribute), angular.copy(items));
console.log($scope.myNewArray);
}
// Function to display the updated JSON
$scope.showNewJson = function() {
return $scope.myNewArray;
}
}]);
Note: This example utilizes AngularJS for data handling.
To view the updated version, visit: Updated JSFiddle link
Below is the corrected JSON structure:
{
"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"
}
]
}
]
}
]
}