1

If I have an angular form like this

<form name="myForm">
  <input type="text" required ng-model="field1" />
  <input type="text" ng-model="field2" />
</form>

When I access the model it will only hold those fields that have values so if both fields have values json will be {"field1":"value1","field2":"value2"}. If only field1 is has a value json will be {"field1":"value1"}. Can I instruct Angular to keep empty fields in the model with null values?

UPDATE:

My controller looks like below. I'm loading the data as json from the server. When the data comes from the server I get this {"field1":"value1","field2":"value2"} but when saveContent is run and only field1 has a value the server gets this {"field1":"value1"}.

var myApp = angular.module('myApp', []);
myApp.controller('contentEditController', ['$scope', '$http',
  function ($scope, $http) {

      $scope.saveContent = function () {
          $http.post("/api/ContentData", $scope.formdata);
      };

      $scope.loadContent = function (contentId) {
          $http.get("/api/ContentData/" + contentId)
              .success(function (response) {
                  $scope.formdata = response;
               });
      }

  }]);

So fields that had values when they came from the server don't get sent back as empty.

-Mathias

Mathias Rönnlund
  • 4,078
  • 7
  • 43
  • 96

2 Answers2

3

Initialize the values on the scope in the controller,

.controller('formcontroller', [ '$scope', function($scope){
  $scope.field1 = "";
  $scope.field2 = "";
})];
MikeDev
  • 114
  • 3
  • Thanks for the answer. What if I don't have the values separately like that, like I put in the updated question? – Mathias Rönnlund Jan 07 '15 at 14:37
  • As long as you're using the ng-model directive to bind the form fields to the scope then you should still be able to initialize them separately, and you should if the field is necessary for the call to the server. – MikeDev Jan 07 '15 at 19:23
1

The proper way to do this is to initialize the variables. You should in your controller have

$scope.field1 = ""
$scope.field2 = ""

or a more crude way to do is in to use ng-init (try not to use ng-init if you can)

<input type="text" required ng-model="field1" ng-init="field1=''"/>
<input type="text" ng-model="field2" ng-init="field2=''"/>
yangli-io
  • 16,760
  • 8
  • 37
  • 47