【问题标题】:ng-change doesn't get fired for email input unless I enter a valid email address除非我输入有效的电子邮件地址,否则不会因电子邮件输入而触发 ng-change
【发布时间】:2015-05-06 18:41:45
【问题描述】:

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

有关实施的更多详细信息,请查看 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);
    }
});

干杯。

【问题讨论】:

  • 这是设计使然,因为输入类型是“电子邮件”。为什么要检查无效电子邮件?
  • 在你自己的指令中使用 $parser 或 $formatter 会给你这个值。

标签: javascript angularjs angularjs-ng-change angularjs-watch


【解决方案1】:

你可以在 keyup 上获取输入元素的值

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

【讨论】:

  • 你是对的!感谢您提供示例。
  • 这个答案是有缺陷的,原因有几个。首先,您依赖于全局变量并使控制器的可测试性降低 - DI 如此深植于 Angular 是有原因的。其次,您完全绕过了ng-model,它可以附加到非文本输入,从而紧密耦合控制器和视图。
【解决方案2】:

是的,它按照设计 ng-change 首先评估表达式(电子邮件或文本),如果其有效,它将调用函数

让我们以文本字段为例。

因此,如果input[text] 中有任何内容(任何文本),它将有效并触发 function(),但如果是电子邮件,则仅当 input[email] 有效且需要进行一些验证时才有效,然后它会触发事件。

同样,$watch 将评估应用于它的值 $scope.$watch("user.email") 在这种情况下 user.email 仅当 input[email] 包含有效值时才会设置。

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

【讨论】:

    【解决方案3】:

    其实是有办法的。您可以使用 $ViewValue。

    在表单中添加一个 ng-form

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

    您可以阅读更多here

    【讨论】:

      猜你喜欢
      • 2010-12-04
      • 1970-01-01
      • 1970-01-01
      • 2019-06-05
      • 2011-08-24
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 2017-03-01
      相关资源
      最近更新 更多