JC Borlagdan
JC Borlagdan

Reputation: 3618

How to pass value from controller to input HTML in angularjs?

How do I pass a value from my controller to <input>tag in my view? I got the data successfully but calling it from the html, it's not working? I don't get any errors, my syntax is just wrong, I tried several syntax base from angularjs documentation, I also tried using ng-value={{data.email}} and even placing double quotes between the value. What is the proper way to do this?

this is my html:

<label class="item item-input">
    <input type="text" placeholder="Email" value={{data.email}} disabled>
</label>

this is my controller:

$http({
    method: 'POST',
    url: 'myservice',
    data: encodedString,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data) {
    for (i = 0; i < data.length; i++) {
        if (data[i].QActivationCode === data[i].token) {
            $scope.userData = data[i];
            Acct.setAcctEmail(data[i].email);
        }

    }
});

Upvotes: 2

Views: 3931

Answers (3)

Suneet Bansal
Suneet Bansal

Reputation: 2702

In angular, ng-model is used to bind the scope values with the html elements. Or we can use {{}} expression if we have to pass the value to the input tags.

Small description about ng-model:

The ngModel directive binds an input , select , textarea (or custom form control) to a property on the scope using NgModelController, which is created and exposed by this directive. ngModel is responsible for: Binding the view into the model, which other directives such as input , textarea or select require.

Corrected html code is attached below:

1. <label class="item item-input">
    <input type="text" placeholder="Email" ng-model="userData.email" disabled>
</label>

2. <label class="item item-input">
    <input type="text" placeholder="Email" value={{userData.email}} disabled>
</label>

Upvotes: 1

Shashank Agrawal
Shashank Agrawal

Reputation: 25797

You can use either ng-model or ng-value. You are using the wrong key in the view i.e. you should use userData.email instead of data.email in the HTML view. (The statement $scope.userData = data[i]; states that you are adding the key userData in the scope not the data):

Using ng-model

<label class="item item-input">
    <input type="text" placeholder="Email" ng-model="userData.email" disabled>
</label>

Using value

 <label class="item item-input">
    <input type="text" placeholder="Email" value={{userData.email}} disabled>
</label>

Since the input field is disabled and we do not need to alter that input field so you should use the 2nd option.

Upvotes: 2

mtamma
mtamma

Reputation: 533

use ng-model

<label class="item item-input">
  <input type="text" placeholder="Email" ng-value="data.email" disabled>
</label>

make sure that object data exist on the scope.

Upvotes: 0

Related Questions