Is there a more effective way to serialize a form with angularjs?

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)
    }
  });
}

Answers:

Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.