使用 Angular 从输入类型的电子邮件中获取价值

Get value from input type email with Angular

如何使用 angularjs 传递 <input type='email'> 的值。我需要在我的表单输入中验证电子邮件地址,并需要用它生成一个密钥。我唯一需要知道的是我应该如何从 input.

中获取值

angular.module('myApp', [])
  .controller('EmailController', function($scope) {
    $scope.hash = "";
    $scope.generateKey = function () {
      var resultKey = $scope.email;
      // TODO: generate key
      
      // Assing value to hash
      $scope.hash = resultKey;
    };
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="EmailController">
  <form>
    <p>Email:&nbsp;<input type="email" ng-model="email" ng-keyup="generateKey()"></p>
    <p><b>Hash:&nbsp;</b>{{hash}}</p>
  </form>
</div>

编辑 1

我可以使用 <input type='text'> 并使用 regex 进行验证,但我想使用 type='email' 作为手机在键盘上显示更多选项。是否存在使用 angular 获取 input 值的方法,即使它不是有效的电子邮件?

如果您希望将无效的电子邮件地址绑定到您的控制器,请使用 ng-model-options="{ allowInvalid: true }"

<input type="email" ng-model="email" ng-keyup="generateKey()" ng-model-options="{ allowInvalid: true }">

编辑: 通常不应将数据绑定到基元,因为原型继承有时会导致绑定到错误的范围。尝试绑定到一个对象,例如 data.email.

编辑: Live example

angular 处理输入值和验证的方式是通过 $parsers。您可以拦截默认解析器,从而在它到达电子邮件验证之前获取值。创建这个小片段以进一步说明我的观点。请注意,我没有使用 .push 来添加我的解析器,而是使用 .unshift。我使用 unshift 而不是 push 因为我想确保我的解析器是列表中的第一个。或者至少,这是我目前添加到列表中的第一个。这将保证它在我的代码运行时已经在列表中的默认解析器之前运行。

var app = angular.module('myApp', []);
    app.controller('EmailController', function($scope) {
      $scope.hash = "";
    });
    app.directive('generateKey', function(){
      return {
        require: ['ngModel'],
        link: function(scope, element, attr, ctrls){
          var ngModel = ctrls[0];

          ngModel.$parsers.unshift(function(text){
            scope.hash = text;
            return text;
          });
        }
      };
  });

如需完整片段,请访问:https://jsbin.com/vabofapigo/edit?html,js,output