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)
}
});
}
To serialize a FormData object into a query string, pass it into the new URLSearchParams() constructor. This will create a URLSearchParams object of encoded query string values. Then, call the URLSearchParams. toString() method on it to convert it into a query string.
The serialize() method creates a URL encoded text string by serializing form values. You can select one or more form elements (like input and/or text area), or the form element itself. The serialized values can be used in the URL query string when making an AJAX request.
In JavaScript, for example, you can serialize an object to a JSON string by calling the function JSON. stringify() . CSS values are serialized by calling the function CSSStyleDeclaration. getPropertyValue() .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With