Ken
Ken

Reputation: 3141

Input field displaying as undefined in Angular

I am trying to get the input value for a form field, but when I use the code below, the value displays as undefined.

Any idea what I'm doing wrong here?

.controller('ContactFormCtrl',
   function (Contacts) {
     var contactForm = this;
     contactForm.contacts = Contacts;
     contactForm.contact = {};
     var mail=contactForm.contact.email;

     contactForm.onchange = function () {console.log(mail);};
 });


<div class="col-sm-6 form-group">
   <label class="control-label" for="email">Email</label>
   <input type="email" id="email" name="email" ng-model="contactForm.contact.email" class="form-control" ng-change="contactForm.onchange()" ng-model-options="{ updateOn: 'blur' }" />
</div>

Upvotes: 0

Views: 1034

Answers (2)

Pankaj Parkar
Pankaj Parkar

Reputation: 136144

As you are using controllerAs syntax then you should use alias there contactForm

<div ng-controller="ContactFormCtrl as contactForm">
 <div class="col-sm-6 form-group">
   <label class="control-label" for="email">Email</label>
   <input type="email" id="email" name="email" ng-model="contactForm.contact.email" class="form-control" ng-change="contactForm.onchange()" ng-model-options="{ updateOn: 'blur' }" />
 </div>
</div>

And the reason it is undefined is you have reinitialized controller contact object after contactForm.contacts = Contacts; which overrides the value of email.

Update

As discussed in chat you want to show email on blur as well as you want to call onchange function on email validate, for that you should have to use combination of directive ng-change with ng-blur then you should get rid off ng-model-options which don't suits your requirement.

Markup

<div ng-controller="ContactFormCtrl as contactForm">
    <form name="myForm">
        <div class="col-sm-6 form-group">
            <label class="control-label" for="email">Email</label>
            <input type="email" id="email" name="email" ng-model="contactForm.contact.email" class="form-control"
            ng-change="myForm.email.$valid && contactForm.onchange()" ng-blur="contactForm.onchange()"/>
        </div>
    </form>
</div>

Upvotes: 0

Amita Sharma
Amita Sharma

Reputation: 21

Update the controller as :

 .controller('ContactFormCtrl',
  function (Contacts) {
    var contactForm = this;
    contactForm.contacts = Contacts;
    contactForm.contact = {};
    contactForm.contact.email="";
    var mail=contactForm.contact.email;

    contactForm.onchange = function () {console.log(mail);};
 });

Currently, there is no email property with "contactForm.contact" object. So you need to initialize the email property and it will not give you undefined error.

Upvotes: 1

Related Questions