1

如果我有这样的角形

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

当我访问模型时,它只会保存那些具有值的字段,因此如果两个字段都有值,json 将是 {"field1":"value1","field2":"value2"}。如果只有 field1 有值,则 json 将为 {"field1":"value1"}。我可以指示 Angular 将模型中的空字段保留为空值吗?

更新:

我的控制器如下所示。我正在从服务器将数据作为 json 加载。当数据来自服务器时,我得到这个 {"field1":"value1","field2":"value2"} 但是当 saveContent 运行并且只有 field1 有一个值时,服务器得到这个 {"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;
               });
      }

  }]);

因此,当它们来自服务器时具有值的字段不会作为空返回。

-马蒂亚斯

4

2 回答 2

3

初始化控制器范围内的值,

.controller('formcontroller', [ '$scope', function($scope){
  $scope.field1 = "";
  $scope.field2 = "";
})];
于 2015-01-07T07:45:32.787 回答
1

正确的方法是初始化变量。你应该在你的控制器中有

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

或更粗略的方法是使用 ng-init (如果可以,尽量不要使用 ng-init)

<input type="text" required ng-model="field1" ng-init="field1=''"/>
<input type="text" ng-model="field2" ng-init="field2=''"/>
于 2015-01-07T07:43:45.543 回答