7

As far as I can tell, AngularJS does not serialize a form field if it is empty. But, I need this fields to be in the JSON that is generated, even if they are empty. I am trying to query that JSON, and it will fail if the fields descriptors are not there. Any tips on how to get AngularJS to do this?

In the example below, if you entered "John" into the name field, and nothing in the optionalval field, the json that is formed is this {name: John}. But I would like it to be like this {name:'John', optionalval:''}. This is in the case of a "create new" form where optional fields might not have any values. But, the fields need to be sent whether they have values or not.

<!doctype html>
<html>
    <head>
        <title>Serialize Test</title>
        <script src="js/angular.min.js"></script>
        <script>
			var app = angular.module('myApp', []);
			app.controller('myCtrl', function($scope, $http) {
				$scope.addnew = function(){
					$http.put('/newthing.json', JSON.stringify($scope.item))
						.success(function(){
						})
						.error(function(){
						});
				};
			});
        </script>
    </head>
    <body 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="optoinalval" ng-model="item.optionalval">

		<button ng-click="addnew()">Serialize</button>
    </body>
</html>

4
  • 1
    shouldn't be an issue if you are using ng-model properly. Provide some code. We can't troubleshoot what we can't see Commented Aug 21, 2015 at 19:26
  • try this way: var dataJSON = { field1 : '1', field2 : ''}, $http{ data : JSON.stringify(dataJSON) Commented Aug 21, 2015 at 19:31
  • Attach a model to your inputs and you should be fine. Show the code please. Commented Aug 21, 2015 at 19:49
  • Thanks for your responses. I have added a code example to help explain the issue. Commented Aug 22, 2015 at 23:50

1 Answer 1

6
+50

One way is to preinitialize model with empty string. For example, by setting model value in controller:

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

Here is a demo:

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>

Sign up to request clarification or add additional context in comments.

5 Comments

You should use initializing from controllers instead of using ng-init. That is not the correct use, see the documentation for more information. docs.angularjs.org/api/ng/directive/ngInit
@cverb Well, this is correct usage of the directive, however you are right that controller usage might be better in this case. Edited.
dfsq and @cverb, thank you for your responses. I marked dfsq's response as the answer but, I was hoping for a different one. My real-world code is dealing with an item that has about 50+ fields, and I was hoping to avoid having to initialize all those fields, and just have a generic "item" controller that could handle the serialization of any form that wanted to use it as a controller. Looks like I'll need to write something for each and every item type. Thanks again!
Well in this no elegant solution here. You will either need to write some code (like custom directive) or add something like ngInit (simplest: ng-init="item.optionalval = ''") to every input that you want to be at least empty string.
dfsq- That might not be such a bad solution. At least all of the item-specific code can be contained within the form so, my JavaScript code can remain agnostic toward the item it is using. My goal is to be able to change only the SQL stored procedures and the html forms when I need to change a property within a particular item...I hope to keep all the other code very loosely coupled. Thank you very much for your suggestions and your follow-up on my comment. Cheers!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.