这是一个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 ??
答案 0 :(得分:1)
您正在推送数组中的变量,以便获得数组。这样做:
$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);
};
答案 1 :(得分:0)
Dnt需要在控制器中进行字符串化,他希望在pre标签中显示我想的检查目的。
$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;
};
将它放在你的html中
<pre>{{ dataShow | json}}</pre>