Add dynamic field to generate specific JSON format
I am trying to create a form with dynamic fields to create JSON to post as
{
"cpu": "1",
"ram": "128",
"env": {
"envname1": "value1",
"envname2": "value2"
}
}
While I have no problem creating cpu and ram, I can't figure out what to create "envname" and "value" because envname must be in the dynamically added field, the first column and the value in the second column.
I also cannot get regular fields and dynamic fields together in the same area.
Please take a look at http://jsfiddle.net/q9dcn7wj/3/ the CPU and RAM fields are ignored. When i change
$scope.inputs = [{id: 'choice1'}];
to
$scope.inputs = {id: 'choice1'};
dynamic fields are ignored. How can I get all the options to represent the entire form as JSON?
source to share
You treat your model inputs
as if it were array
and object
.
I suggest you create a property variables
in your model input
and push / splice on it.
I have updated the JSFiddle to match the code below:
JavaScript :
var app = angular.module('myApp', []);
app.controller('MyCtrl', ['$scope', function ($scope) {
$scope.inputs = { variable: [] };
$scope.addInput = function(){
$scope.inputs.variable.push({name:'', value:''});
}
$scope.removeInput = function(index){
$scope.inputs.variable.splice(index,1);
}
}]);
Html
<div ng-app="myApp" ng-controller="MyCtrl">
<input type="text" ng-model="inputs.cpu" />cpu<br />
<input type="text" ng-model="inputs.ram" />ram
<div ng-repeat="input in inputs.variable">
<input type="text" ng-model="input.name" />
<input type="text" ng-model="input.value" />
<button ng-click="removeInput($index)">Remove</button>
</div>
<button ng-click="addInput()">add input</button>
<br />
<strong><label for="userDebugText">JSON:</label></strong>
<textarea id="userDebugText">{{inputs|json}}</textarea>
</div>
source to share