如何强制AngularJS序列化空表单字段

时间:2015-08-21 19:23:35

标签: json angularjs forms serialization

据我所知,如果表单字段为空,AngularJS不会序列化表单字段。但是,我需要将这些字段放在生成的JSON中,即使它们是空的。我试图查询该JSON,如果字段描述符不在那里它将失败。有关如何让AngularJS执行此操作的任何提示?

在下面的示例中,如果您输入了" John"在name字段中,在optionalval字段中没有任何内容,所形成的json是{name:John}。但我希望它像{姓名:' John&#39 ;, optionalval:''}。这是一个"创建新的"表单,其中可选字段可能没有任何值。但是,无论是否有值,都需要发送字段。



 String city = Paper.get("city");




1 个答案:

答案 0 :(得分:6)

一种方法是使用空字符串预初始化模型。例如,通过在控制器中设置模型值:

$scope.item = {optionalval: ''};

这是一个演示:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
  $scope.item = {optionalval: ''};
  $scope.addnew = function() {
    $http.put('/newthing.json', JSON.stringify($scope.item))
    .success(function() {})
    .error(function() {});
  };
});
<script src="https://code.angularjs.org/1.4.3/angular.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">
  <label for="name">Name:</label>
  <input type="text" id="name" ng-model="item.name" required>
  
  <label for="optionalval">Don't put anything here:</label>
  <input type="text" id="optionalval" ng-model="item.optionalval">

  <button ng-click="addnew()">Serialize</button>
  <pre>{{item | json}}
</div>