简体   繁体   中英

Generate json from angularjs form

This is an AngularJS problem; I have a simple form:

<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>

Here is the Script::

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); 
    };

});

The script Outputs array:

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

But I want to generate 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
    }
}

how do I get that json??

You are pushing the variables in an array so you will obtain an array. Do this instead:

$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); 
};

Dnt need to stringify in controller, He wants to show in pre tag for checking purpose i thought.

$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 = qus; 
};

Put this in your html

<pre>{{ dataShow | json}}</pre>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM