作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
据我所知,如果表单字段为空,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/
我尝试通过正则表达式将文本中的单引号更改为双引号。 (单字)示例:我走了。 You gona fly to planet 'Ziqtos' => 我需要在 I'm 中保留单引号,并在 You gona
我正在构建一个 API,其中大部分将包含 JSON 和 HTML 内容。但是一些非常具体的端点只呈现 true 或 false,并且还在 POST 中接受 true 或 false。这是请求或响应的整
我是一名优秀的程序员,十分优秀!