【问题标题】:Drop down list and values下拉列表和值
【发布时间】:2017-06-22 08:11:42
【问题描述】:

我在设置下拉列表的值时遇到问题。我在这里粘贴我的代码。

HTML 代码:

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

这是我的 angularjs 代码:

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

最后这是我的 express.js 设置。我将表单详细信息保存到文件的位置。

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

输出为json格式:

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

我希望输出应该是形式。

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

在标记列中,我想要学生姓名而不是班级名称。谁能帮我 。谢谢 。

【问题讨论】:

    标签: javascript angularjs json node.js html


    【解决方案1】:

    您在 html 的 ng-model 指令中使用了 setmarks.marks.5thclass。因为 5thclass 被视为标记对象的属性。这就是为什么它被赋予"marks":{"5thclass":66} .触发保存事件后,您必须在控制器中手动创建您期望的 json 对象。如下。希望对您有所帮助。

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

    注意: 不要在 setmarks.5thclass 等属性中使用数字作为第一个字符。这将在编译表达式时被视为语法错误并引发错误。

    【讨论】:

    • 太好了,很高兴听到这个消息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多