naik3 naik3 - 4 years ago 53
JSON Question

Drop down list and values

I having a problem in setting the values of dropdown list. Here I am pasting my code.

HTML Code:

<form ng-submit="save()">
<table style=" table-layout: fixed;" class="table">
<thead>
<tr>
<th>Section</th>
<th>Names</th>
<th>Marks</th>
</tr>
</thead>
<tbody>
<tr>
<td>5th class</td>
<td>
<select id="5thclass" ng-model="setmarks.5thclass" ng-options="val for val in studentname">
<option ng-init="setmarks.5thclass=studentname[0]" selected="selected"></option>
</select>
</td>
<td>
<input type="number" name="5thclass" ng-model="setmarks.marks.5thclass"/>
</td>
</tr>
</tbody>
</table>
<div class="sub" class="btn-group">
<input id="savebutton" type="submit" ng-click="Submit" value="Save" class="btn btn-primary">
</div><br />
</form>


Here is my angularjs code :

$scope.studentname = ["abc","pqr","xyz"];

$scope.save = function(){

$http.post('/savemarks', $scope.setmarks).success(function(data){
console.log("posted data successfully");
console.log( JSON.stringify(data));
}).error(function(data){
console.error("Error posting data");
})
}


And finally here is my express.js set up. Where I am saving the form details in to file.

app.post('/savemarks',urlencodedParser,function(req,res){
fs.appendFile(writecost_file,JSON.stringify(req.body,null,1),function(err){
if(err){
console.log(err);
}else{
console.log("File saved");
}
});
});


Output is in the json form:

{"5thclass":"abc","marks":{"5thclass":66}}


I want output should be of form.

{"5thclass":"abc","marks":{"abc":66}}


In the marks column i want student name instead of class name. Can any one help me . Thanks .

Answer Source

You are using setmarks.marks.5thclass inside the ng-model directive in your html. Because of that 5thclass is treated as a property of the marks object. That is why it is given as "marks":{"5thclass":66} . You have to create the json object you are expecting manually in controller after save event is fired. As below. Hope this will help to you.

 var st = '{"5thclass" : "' + $scope.setmarks.5thclass + '","marks":{"' + $scope.setmarks.5thclass + '":' + $scope.setmarks.marks.5thclass + '} }';
 var obj = JSON.parse(st);

Note: Don't use number as first character in property like setmarks.5thclass. This will consider as a syntax error while compiling the expression and will throw error.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download