Notes
Notes

Reputation: 3

Create dynamic form and validate/post it in AngularJS

I have in AngularJS a login form with a username and password input field. Above there is a button to load the register form. Then an email field will be added to the form.

But when I submit the register form, only the username and password input fields will be posted and not the email field.

Send Data after Login: {"username":"test","password":"test"}
Send Data after Register: {"username":"test","password":"test"} 

Do you know why?

I created a Plnkr to demonstrate the problem: http://embed.plnkr.co/HBEfITT3SNSZv44hj2x3/preview

Upvotes: 0

Views: 503

Answers (1)

JB Nizet
JB Nizet

Reputation: 692151

Your additional field is inside an element with

ng-if="register"

ng-if is a directive that creates its own scope. So, when something is entered into the field <input ng-model="email" ...>, an email attribute is created and populated in the ng-if scope, instead of being created in the controller scope.

Rule of thumb: always have a dot in your ng-model, and always initialize the form model in the controller:

$scope.formModel = {};

<input ng-model="formModel.email" ...>

This will also make things simpler, since to post the form, all you'll have to do is something like

$http.post(url, $scope.formModel).then(...);

Upvotes: 1

Related Questions