pizzarob
pizzarob

Reputation: 12049

Use ng-model on Input Field that Has Value Set From Another Model Angular

I have an input field that will be pre-populated with the users info if that data is available (email address, first name, etc.)

I am setting the value of the input field with $scope.userData initially, and when I set an ng-model attribute on the input field the value on the front-end is then blank.

Example:

Works to show value (input field has users email:

<input class="text-input" type="email" value="{{data.email}}">

Doesn't Work (blank input field):

<input class="text-input" type="email" ng-model="formData.email" value="{{data.email}}">

I see why this doesn't work, formData.email is blank and it seems the model will overwrite the value, but I need to save this into formData to then make a POST request to my service upon submission of the form.

I am new to angular and would like to do this with angular rather than using jQuery as a crutch.

So how would I set the email field to a model to use during form submission, but populate the value of the email field with the initial email data, if present?

Upvotes: 0

Views: 1688

Answers (2)

Hanra091
Hanra091

Reputation: 101

What you want to do is execute the following code when the form loads:

formData.email = data.email

Angular has the ngInit method for this purpose. Let's say you've set up a function somewhere called initializeEmail which does this. You would then need to add something like this inside your form tag (or anywhere which knows what the formData is):

<form ng-init="initializeEmail(data.email)>

Then, when angular loads up it'll see this function and set the formData's email field appropriately.

Upvotes: 1

iamkd
iamkd

Reputation: 94

AngularJS uses two-way binding.

It means that if you write something in input with ng-model="formData.email", the scope value will change and in controller it will be accessible as $scope.formData.email. And if you change the value of $scope.formData.email in controller, it will automatically update the value of <input /> in view.

To set the default address, you should remove the value attribute from input and set the value of $scope.formData.email in JavaScript at the beginning of controller.

I recommend you to read the official basic tutorial. Everything is very well described there.

Upvotes: -1

Related Questions