这是一个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);
};

09-17 04:55