[英]How to create create JSON object ( of form elements) of dynamic html form?
[英]How to create json object for html form using AngularJS?
我现在正在学习angularJS。 如何为给定的html
表单创建json对象。 我可以使用jQuery
,但是我需要在AngularJS
做到这一点,请让我知道如何在angularJS中做到这一点,谢谢。
更好的是,无需序列化,您可以使用ng-model这样进行。
var app = angular.module('demoApp', []); app.controller('demoController', function($scope) { $scope.formData = {} $scope.serialize = function($event){ console.log($scope.formData) alert(JSON.stringify($scope.formData)) $event.preventDefault() } });
<!DOCTYPE html> <html ng-app="demoApp"> <head> <script src="https://code.angularjs.org/1.4.9/angular.js" ></script> </head> <body ng-controller="demoController"> <h2>Form</h2> <form action="" method="post" id="formid" name="testForm"> First Name: <input type="text" ng-model="formData.Fname" maxlength="50" size="12" /> <br/> Last Name: <input type="text" ng-model="formData.Lname" maxlength="50" size="12" /> <br/> Select a Level of Education: <br/> <select ng-model="formData.education"> <option value="Jr.High">Jr.High</option> <option value="HighSchool">HighSchool</option> <option value="College">College</option> </select> <br/> <p> <input type="submit" ng-click="serialize($event)" /> </p> </form> </body> </html>
我不认为需要序列化表单数据,我们可以在控制器中设置一个对象并将模型作为属性添加到其中。 这是Codepen 。
查看:
<form name="contactForm" class="col-md-6" ng-app="app" ng-controller="bodyCtrl">
<div class="form-group">
<label for="exampleInputEmail1">Firstname</label>
<input type="text" class="form-control" ng-model="simpleForm.first_name">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Lastname</label>
<input type="text" class="form-control" ng- model="simpleForm.last_name">
</div>
<div class="form-group">
<select class="form-control" name="" id="" ng-options="option.value as option.label for option in educationOptions" ng- model="simpleForm.education">
</select>
</div>
<button type="submit" class="btn btn-default" ng-click="toggleShow()">Submit</button>
<pre ng-hide="!show">
<code>
{{simpleForm|json}}
</code>
</pre>
控制器:
var app = angular.module('app', []);
app.controller('bodyCtrl', function($scope) {
$scope.show = false;
$scope.simpleForm = {};
$scope.educationOptions = [{
'label': 'Jr.High',
'value': 'Jr.High'
}, {
'label': 'HighSchool',
'value': 'HighSchool'
}, {
'label': 'College',
'value': 'College'
}]
$scope.simpleForm.education = $scope.educationOptions[0].value;
$scope.toggleShow = function() {
$scope.show = !$scope.show
}
})
您可能要参考这个链接了解更多关于数据绑定 。而这一个 ,如果你是从jQuery的背景的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.