mikem
mikem

Reputation: 31

Add dynamic field to create specific JSON format

Im trying to create a form with dynamic fields to create a JSON to post like this

{
"cpu": "1",
"ram": "128",
"env": {
    "envname1": "value1",
    "envname2": "value2"
}
}

While i have no problem to create cpu and ram i can not figure out to create "envname" and "value" because envname should be in a dynamic added field the first column and the value in second column.

I also can not get the regular fields and the dynamic fields together in one scope.

Please have a look at http://jsfiddle.net/q9dcn7wj/3/ cpu and ram fields are ignored. When i change

    $scope.inputs = [{id: 'choice1'}];

to

     $scope.inputs = {id: 'choice1'};

the dynamic fields are ignored. How do i get everything in the scope to submit the whole form as JSON?

Upvotes: 3

Views: 753

Answers (1)

Michael Robinson
Michael Robinson

Reputation: 29508

You are treating your inputs model as if it is both an array and an object.

I suggest you create a variables property on your input model and push/splice on that.

I've updated your JSFiddle, relevant 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>

Upvotes: 1

Related Questions