gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 04:26:36 25 4
gpt4 key购买 nike

据我所知,如果表单字段为空,AngularJS 不会序列化它。但是,我需要此字段位于生成的 JSON 中,即使它们为空。我正在尝试查询该 JSON,如果字段描述符不存在,它将失败。关于如何让 AngularJS 做到这一点有什么建议吗?

在下面的示例中,如果您在 name 字段中输入了“John”,并且在 optionalval 字段中没有输入任何内容,则形成的 json 就是 {name: John}。但我希望它像这样 {name:'John', optionalval:''}。这是在“创建新”表单的情况下,其中可选字段可能没有任何值。但是,无论字段是否有值,都需要发送。

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

最佳答案

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

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

关于json - 如何强制 AngularJS 序列化空表单字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32147916/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com