Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
333 views
in Technique[技术] by (71.8m points)

javascript - 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)
    }
  });
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...