有没有更有效的方法来使用angularjs序列化表单?

Web*_*ent 27 javascript serialization angularjs

有没有办法为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)
    }
  });
}
Run Code Online (Sandbox Code Playgroud)

Stu*_*tuR 66

这不是您应该如何使用AngularJS访问表单数据.表单中的数据应该绑定在范围内.

因此,使用一个对象,例如$ scope.formData,它将包含您的所有数据结构,然后您的每个表单元素都应该使用ng-model绑定到此.

例如:

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);
    };
}
Run Code Online (Sandbox Code Playgroud)

提交上面的表单时,$ scope.formData将包含表单的对象,然后可以在您的AJAX请求中传递.例如:

Object {name: "stu", address: "england"} 
Run Code Online (Sandbox Code Playgroud)

要回答您的问题,没有更好的方法来使用AngularJS"序列化"表单数据.

但是你可以使用jQuery:$ element.serialize(),但如果你想正确使用Angular,那么请使用上面的方法.

  • 当您在页面上有多个表单时,这将无法正常工作,例如作为ng-repeat指令的一部分... (3认同)
  • @Kevin查看动态创建表单的ng-form(例如作为ng-repeat指令的一部分)http://scotch.io/tutorials/javascript/building-dynamic-angular-forms-with-ngrepeat-and-ngform (2认同)