ng变化不会'除非我输入了有效的电子邮件地址,否则我不会因为输入电子邮件而被解雇

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

本文关键字:输入 因为 电子邮件 有效 变化 非我 ng 电子邮件地址      更新时间:2023-09-26

无效电子邮件输入的模型值始终未定义。我希望能够检查用户是否输入了任何文本(即使它还不是有效的电子邮件地址)。

有关实现的更多详细信息,请查看plnkr: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>

控制器:

    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);
    }
});

干杯。

实际上有一种方法。您可以使用$ViewValue。

将ng表单添加到表单

body ng-controller="MainCtrl">
    <form name="myForm" ng-form="myForm">
      <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>

然后在控制器中,您应该能够获取值

   var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.user = {};
    $scope.changed = function(){
      console.log("Changed: "+$scope.myForm.email.$viewValue);
    }
    $scope.keyUp = function(){
      console.log("KeyUp: "+$scope.myForm.email.$viewValue);
    }
});

您可以在此处阅读更多信息

是的,根据设计更改,首先评估表达式(电子邮件或文本)是否有效,它将调用函数

让我们以文本字段为例。

因此,如果input[text]中有任何内容(任何文本),它将是有效的并激发函数(),但在电子邮件的情况下,它只有在input[email]有效时才有效,这需要进行一些验证,然后它将激发事件。

$watch也是如此,它将评估应用于它的值$scope.$watch("user.email")(在本例中为user.email),该值仅在input[email]包含有效值时设置。

ng-keyup将调用"始终在键盘上"事件,因此它将在每个代码中调用function()

您可以在keyup 上获得输入元素的值

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