有没有与序列化一个angularjs形式的更有效的方法? [英] Is there a more effective way to serialize a form with angularjs?
问题描述
有没有办法来序列化功能angularjs?
我的帖子貌似现在这个权利。
$ scope.signup_submit =功能(){
VAR FORMDATA = {
用户名:$ scope.username,
FULL_NAME:$ scope.full_name,
电子邮件:$ scope.email,
密码:$ scope.password,
confirm_password:$ scope.confirm_password
} $ HTTP({
方法:POST,
网址:'/注册,
数据:FORMDATA,
})。成功(功能(数据){
如果(data.status =='成功'){
警报('所有好');
}其他{
警报(data.msg)
}
});
}
这是不是你应该如何使用AngularJS访问表单数据。在你的表单中的数据应该在范围内的约束。
因此,使用一个对象,如$ scope.formData,其中将包含所有的数据结构,那么每个表单元素应该绑定到该用NG-模式。
例如:
http://jsfiddle.net/rd13/AvGKj/13/
<形式NG控制器=MyCtrlNG提交=提交()>
<输入类型=文本名称=名字吴模型=formData.name>
<输入类型=文本名称=地址NG模型=formData.address>
<输入类型=提交值=提交表单>
< /表及GT;功能MyCtrl($范围){
$ scope.formData = {}; $ scope.submit =功能(){
的console.log(this.formData);
};
}
在上面的表单提交$ scope.formData将包含您的形式,然后可以在您的AJAX请求传递的对象。例如:
对象{名字:STU,地址:英格兰队}
要回答你的问题,有没有更好的方法,使用AngularJS为连载表单数据。
您可以但是使用jQuery:$ element.serialize(),但是如果你要使用正确的角度,然后用上面的方法去
。Is there a way to serialize function for angularjs?
my post looks like this right now.
$scope.signup_submit = function () {
var formData = {
username: $scope.username,
full_name: $scope.full_name,
email: $scope.email,
password: $scope.password,
confirm_password: $scope.confirm_password
}
$http({
method: "POST",
url: '/signup',
data: formData,
}).success(function (data) {
if (data.status == 'success') {
alert('all okay');
} else {
alert(data.msg)
}
});
}
This isn't how you should access form data using AngularJS. The data in your form should be bound within the scope.
So use an object, e.g. $scope.formData, which will contain all your data structure, then each of your form elements should be bound to this using ng-model.
e.g:
http://jsfiddle.net/rd13/AvGKj/13/
<form ng-controller="MyCtrl" ng-submit="submit()">
<input type="text" name="name" ng-model="formData.name">
<input type="text" name="address" ng-model="formData.address">
<input type="submit" value="Submit Form">
</form>
function MyCtrl($scope) {
$scope.formData = {};
$scope.submit = function() {
console.log(this.formData);
};
}
When the above form is submitted $scope.formData will contain an object of your form which can then be passed in your AJAX request. e.g:
Object {name: "stu", address: "england"}
To answer your question, there is no better method to "serialize" a forms data using AngularJS.
You could however use jQuery: $element.serialize(), but if you want to use Angular properly then go with the above method.
这篇关于有没有与序列化一个angularjs形式的更有效的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!