javascript - 从 angularjs 表单生成 json

标签 javascript json angularjs

这是一个 AngularJS 问题;我有一个简单的表格:

<input type="text"
       class="form-control"
       id="qus"
       placeholder="Enter Question"
       ng-model="qus">
    <input type="text"
           class="form-control"
           id="op1"
           placeholder="Option 1"
           ng-model="op1">
        <label>
            <input type="checkbox"
                   ng-model="correct1">Correct
        </label>
        <button class="form-control btn btn-primary"
                ng-click="save()">Save</button>
        <pre  ng-bind="dataShow"></pre>

这是脚本::

var app = angular.module('qApp', []);
app.controller('qCtrl', function($scope) {
    var set = [];

    $scope.save = function (){
        var op1 = [];  // Moved it inside the save method
        if($scope.correct1!==true){$scope.correct1=false;}      
        op1.push($scope.op1, $scope.correct1);
        var qus = [$scope.qus, op1];
        set.push(qus);
        $scope.dataShow = JSON.stringify(set); 
    };

});

脚本输出数组:

[["what is your name?", ["Alex", false ], ["Hervy", false ], ["Rico", true ], ["Tom", false ] ] ]

但是我想生成json:

{
    qus :"what is your name?",
    option1 : {

        ans : "Alex",
        cor : false
    },
    option2 : {

        ans : "Hervy",
        cor : false
    },
    option3 : {

        ans : "Rico",
        cor : true
    },
    option4 : {

        ans : "Tom",
        cor : false
    }
}

如何获取该 json?

最佳答案

您将变量插入数组中,因此您将获得一个数组。改为这样做:

$scope.save = function (){
    var op1 = {};

    if($scope.correct1!==true) { $scope.correct1=false; }

    op1 = { ans: $scope.op1, cor: $scope.correct1 };

    var qus = {
        qus :"what is your name?",
        options1: op1
    };

    $scope.dataShow = JSON.stringify(qus); 
};

关于javascript - 从 angularjs 表单生成 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32627097/

相关文章:

java - 在下拉菜单中拉取 json 文件

javascript - Angular : How to allow selecting values outside of ngOptions

javascript - 错误 : <line> attribute y1: Expected length, "NaN"

javascript - 在 800 x 600 上跟踪鼠标移动并在 1024 x 768 上显示

JavaScript JSON 数组编号不一致

javascript - AngularJS 设置多选下拉列表的值

javascript - 为什么我的 jsangular 没有在我的范围内循环?

javascript - 如何在元素的参数中使用变量?

javascript - wavesurfer.js destroy() 导致未捕获( promise 中)DOMException : Cannot close a context that is being closed or has already been closed

android - 是否可以使用 JSON 在 LibGDX 的 TextButtonStyle 中使用两种字体?