添加动态字段以创建特定的 JSON 格式

Add dynamic field to create specific JSON format

本文关键字:JSON 格式 创建 动态 字段 添加      更新时间:2023-09-26

我试图创建一个带有动态字段的表单来创建一个 JSON 来像这样发布

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

虽然我在创建 cpu 和 ram 方面没有问题,但我无法弄清楚创建"envname"和"value",因为 envname 应该在动态添加字段中的第一列和第二列中的值。

我也无法将常规字段和动态字段放在一个范围内。

请看一下 http://jsfiddle.net/q9dcn7wj/3/CPU 和 RAM 字段将被忽略。当我改变时

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

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

动态字段将被忽略。如何获取范围内的所有内容以将整个表单提交为 JSON?

您正在将inputs模型视为既是array又是object

我建议您在input模型上创建一个variables属性并在其上进行推送/拼接。

我已经更新了您的JSFiddle,下面的相关代码:

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>