0

I want to do a simple comparison of 2 emails.

I'm curious about how data syncs between the Controller and the models. I attached a screenshot where you can the the difference in the outputs and the actual view/model values.

Difference between the controller values and model values

ng-keydown="equal(newNote.email)" is used on the input field.

  • What is the reason for this behaviour?
  • Is there some kind of pending $digest cycle going on under the hood of Angular?
  • How can I make this work?

Thanks in advance!

Roland Jegorov
  • 789
  • 1
  • 11
  • 27

1 Answers1

0

I think you are printing (console.log) values on change event and it prints old value.

You can use a watcher to compare values

$scope.watch('$scope.email2', function(oldval, newval){
        if ($scope.email1 == newval){
              dosomething();
        }
});

Or you can use ng-keyup like this

<input type='text' ng-model='email2' ng-keyup='validate_email()' />

and in controller

$scope.validate_email = function(){
    if ($scope.email1 == newval){
         dosomething();
    }
}
Zohaib Ijaz
  • 21,926
  • 7
  • 38
  • 60
  • This indeed gave me the correct result in the log, but in a strange manner – only after 2 times changing the value of the field. What I mean is that the watcher was called after 2 digest cycles I assume. :) – Roland Jegorov Jan 23 '16 at 19:27
  • Well, yes, this works, as I found out myself in the comments above. However, to accept this as an answer I would like to know the behind-the-scenes process of why exactly this works. :) – Roland Jegorov Jan 23 '16 at 19:47
  • keyup works becuase at that time model has changed and that function was called after value has been changed and model has been updated that's why it works. but when you call it ng-keydown or ng-change, it's start of the change and it has not yet completed. It just says that something is going to happen but model has not been changed untill validation or console.log is executed. I think it's very simple to understand. – Zohaib Ijaz Jan 23 '16 at 19:53
  • It is simple. I was just hoping that I would receive a pro tip on the topic. Still, would be nice if you refactor your controller code so it uses not a generic variable, but a $scope.email2 because the $watch fn is no longer used in your 2nd example. – Roland Jegorov Jan 23 '16 at 20:02