iamsar
iamsar

Reputation: 1130

AngularJS form doesn't send data

Running into a weird problem with Angular forms (running 1.2 rc.2). If I leave the form without a name and prepend each model with a common name, the form sends fine. If I remove the prepended name from each model and give the form that name, the submit action doesn't bind the data and the form tries to send an empty request payload.

This model works fine, except Angular's form validation doesn't instantiate

<form ng-submit="sendForm()">
    <input type="text" ng-model="my_form.fullname">
    <button type="submit">Submit</button>
<form>

.

app.controller("MyCtrl", function($scope, $http) {
    $scope.sendForm = function() {
        $http({ method:'POST', url: '...', data: $scope.my_form; })
            .then(function(result) { alert("The form was sent"); },
                function(reason) { alert("There was a problem"); });
    }
}

So now if I add a name attribute to my form and remove it from the models, the form tries to send empty data...

<form name="my_form" ng-submit="sendForm()">
    <input type="text" ng-model="fullname">
    <button type="submit">Submit</button>
<form>

It seems like my_form no longer exists. In fact, if I don't initialize $scope.my_form = {} on the controller the form won't even send an empty object.

Any advice on how to get the second method to work?

Upvotes: 1

Views: 3618

Answers (1)

Brian Genisio
Brian Genisio

Reputation: 48137

When you give the form a name, that name becomes a variable with meta-data about the fields... dirty flags, errors, etc. It doesn't actually hold the data.

So, when you set ng-model to fullname, the value isn't being set on the my_form object, it is being set directly on your $scope.

Personally, I prefer to do it this way:

<form name="my_form" ng-submit="sendForm(formData)">
    <input type="text" ng-model="formData.fullname">
    <button type="submit" ng-disabled="my_form.$invalid">Submit</button>
<form>

Then your code looks like this:

app.controller("MyCtrl", function($scope, $http) {
    $scope.sendForm = function(formData) {
        $http({ 
             method:'POST', 
             url: '...', 
             data: formData 
        })
        .then(
            function(result) { 
                alert("The form was sent"); 
            },
            function(reason) { 
                alert("There was a problem"); 
            }
        );
    }
}

Upvotes: 5

Related Questions