有没有办法序列化 angularjs 的函数?
我的帖子现在看起来像这样。
$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)
}
});
}
最佳答案
这不是使用 AngularJS 访问表单数据的方式。表单中的数据应绑定(bind)在范围内。
所以使用一个对象,例如$scope.formData,它将包含您的所有数据结构,然后您的每个表单元素都应该使用 ng-model 绑定(bind)到此。
例如:
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);
};
}
提交上述表单后,$scope.formData 将包含表单的一个对象,然后可以在 AJAX 请求中传递该对象。例如:
Object {name: "stu", address: "england"}
为了回答您的问题,没有更好的方法使用 AngularJS“序列化”表单数据。
但是,您可以使用 jQuery:$element.serialize(),但如果您想正确使用 Angular,请使用上述方法。
关于javascript - 有没有更有效的方法来使用 angularjs 序列化表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15877212/