1

I have an input of type email:

<input type="email" ng-model="user.email" name="email" required>

Now I need to execute some code whenever the input is changed. Adding an ng-change="emailInputChanged()" only executes my method, in case the entered string is a valid e-mail address, but I need the callback to be executed with every keystroke, even though the input does not validate. (same issue of course when watching the model à la $scope.$watch('user.email', emailInputChanged).

Any angular way to do so?

3 Answers 3

2

I suggest to use the onInput event: http://www.w3schools.com/jsref/event_oninput.asp Create a custom directive and listen for the "input" event on your text field element.

Example of the directive implementation:

function OnInput() {
  return {
    restrict: 'A',
    template: '',
    scope: {
      whenInputChanged: '&'
    },
    link: function($scope, $element, $attrs) {
      $element.on('input', $scope.whenInputChanged);
    }
  };
}

angular.module('App')
  .directive('onInput', OnInput);

To apply the event listener in the template:

<input type="email" on-input when-input-changed="change()" name="email" required/>

Enjoy!

Sign up to request clarification or add additional context in comments.

2 Comments

Woohooo, that looks awesome! Thanks!
Dmitri, really neat solution. That's the beauty of angular.
2

since you have given the type as email it will call the ng-change only when its a valid so remove the type attribute

1 Comment

That does not help, the function does not even get called when the input does not validate, as stated.
2

Use ng-keyup instead. This would be the same even with basic (native or jQuery) events, as form will react normally only on field blur.

To catch also paste events, use the ng-paste directive (see https://code.angularjs.org/1.4.6/docs/api/ng/directive/ngPaste)

3 Comments

It will not work for the case when user pasts the email using mouse click paste
Pasting seems like an edge case, so this solution seems almost perfect. Still: Any way to cover the described case, @DmitriPavlutin?
There is a good event "input", which could cover your problem. w3schools.com/jsref/event_oninput.asp But it should be adapted to Angular.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.