2013-04-08 71 views
26

有沒有一種方法來爲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) 
    } 
    }); 
} 
+1

你試過了嗎:$ element.serialize()? – StuR 2013-04-08 10:51:20

+0

是的,它返回undefined函數序列化 – 2013-04-08 10:53:45

+2

我認爲他的意思是$(元素).serialize();你當然需要讓JQuery來實現這一點。 – ganaraj 2013-04-08 11:36:34

回答

62

這不是你應該如何使用AngularJS訪問表單數據。表單中的數據應該在範圍內綁定。

因此,使用一個對象,例如, $ scope.formData,它將包含您的所有數據結構,然後使用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); 
    }; 
} 

當上述表單提交$ scope.formData將包含您的形式,然後可以在你的AJAX請求傳遞的對象。例如:

Object {name: "stu", address: "england"} 

要回答你的問題,沒有更好的方法來使用AngularJS「序列化」表單數據。您可以使用jQuery:$ element.serialize(),但是如果您想正確使用Angular,請使用上述方法。

+3

當你在一個頁面上有多個表單時,這不會很好。作爲ng-repeat指令的一部分... – Kevin 2014-03-30 22:39:14

+2

@Kevin查看ng形式的動態創建表單(例如,作爲ng-repeat指令的一部分) http://scotch.io/tutorials/javascript/building -dynamic-angular-forms-with-ngrepeat-and-ngform – 2014-07-16 01:45:10

+0

我認爲這個問題是關於序列化表單的。 – 2017-04-14 13:33:03

相關問題