Search code examples
javascriptangularjsangularjs-ng-changeangularjs-watch

ng-change doesn't get fired for email input unless I enter a valid email address


Model value for invalid email input is always undefined. I would like to be able to check if the user has entered any text (even if it's not yet a valid email address).

Please check plnkr for more details on the implementation: http://plnkr.co/edit/qV2eqGFhPvZSZKexDVF2?p=preview

Html:

<body ng-controller="MainCtrl">
    <form>
      <div>
        <label for="email">Email address</label>
            <input ng-keyup="keyUp()" ng-change="changed()" type="email" name="email" id="email" ng-model='user.email'/>
        </div>
    </form>
  </body>

Controller:

    var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.user = {};
  $scope.$watch('user.email', function (val){
      console.log("Watch: "+$scope.user.email);
    });
    $scope.changed = function(){
      console.log("Changed: "+$scope.user.email);
    }
    $scope.keyUp = function(){
      console.log("KeyUp: "+$scope.user.email);
    }
});

Cheers.


Solution

  • You could get the value of the input element on keyup

    $scope.keyUp = function(){
       console.log('value: ', event.target.value)
    }