本文介绍了有没有更有效的方法来使用 angularjs 序列化表单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法为 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)
    }
  });
}

推荐答案

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

This isn't how you should access form data using AngularJS. The data in your form should be bound within the scope.

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

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.

例如:

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 请求中传递该对象.例如:

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"}

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

To answer your question, there is no better method to "serialize" a forms data using AngularJS.

然而,您可以使用 jQuery:$element.serialize(),但如果您想正确使用 Angular,请使用上述方法.

You could however use jQuery: $element.serialize(), but if you want to use Angular properly then go with the above method.

这篇关于有没有更有效的方法来使用 angularjs 序列化表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-17 19:21
查看更多