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

时间:2017-06-14 15:44:37

标签: angularjs input angularjs-scope

如何使用<input type='email'>传递angularjs的值。我需要在表单输入中验证电子邮件地址,并且需要生成一个密钥。我唯一需要知道的是如何从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',在键盘上显示更多选项。是否存在使用input获取angular值的方法,即使它不是有效的电子邮件?

2 个答案:

答案 0 :(得分:2)

如果您希望将无效的电子邮件地址绑定到您的控制器,请使用Sub loopFiles() Dim fso As New FileSystemObject Dim fil As File Dim fold As Folder Dim yourfolder As String Dim UpOneDir As String Set fold = fso.GetFolder(Application.ActiveWorkbook.Path) For Each fil In fold.Files UpOneDir = Left(fil.Path, Len(fil.Path) - Len(fil.Name) - 1 - Len(Split(Left(fil.Path, Len(fil.Path) - Len(fil.Name) - 1), "\")(UBound(Split(Left(fil.Path, Len(fil.Path) - Len(fil.Name) - 1), "\"))))) Sub FindIt() Selection.HomeKey Unit:=wdStory With Selection.Find .ClearFormatting .Text = "Aircraft Survey","Cc:","UTAS","Inserted in the word document is a pdf file" .Forward = True .Wrap = wdFindStop .Format = False .MatchCase = False .MatchWholeWord = False .MatchAllWordForms = False .MatchSoundsLike = False .MatchWildcards = True Do While .Execute If InStr(1, fil.Text, "Aircraft Survey","Cc:","UTAS","Inserted in the word document is a pdf file") > 0 Then Application.Workbook.Open fil.Path ActiveWorkbook.Close fil.Delete True End If Loop End With End Sub End Sub

ng-model-options="{ allowInvalid: true }"

编辑:您通常不应该将数据绑定到基元,因为原型继承有时会导致绑定到错误的范围。尝试绑定到对象,例如<input type="email" ng-model="email" ng-keyup="generateKey()" ng-model-options="{ allowInvalid: true }">

修改: Live example

答案 1 :(得分:1)

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