按Enter键时使用AngularJS验证表单

按Enter键时使用AngularJS验证表单,angularjs,angularjs-directive,Angularjs,Angularjs Directive,我在AngularJS代码中对字段进行了描述: input.form-control(type='password' placeholder='password' id='passwordInput' name='passwordInput' ng-model='credentials.password ng-enter='loginByEnter(credentials,loginForm.

我在AngularJS代码中对字段进行了描述:

    input.form-control(type='password' placeholder='password' id='passwordInput'                                        
    name='passwordInput' ng-model='credentials.password
    ng-enter='loginByEnter(credentials,loginForm.$valid)'                                          
    ng-maxlength='{{passwordMaxLen}}'   required form-control)
正在讨论的行是ng,请输入一。loginByEnter的功能是:

$scope.loginByEnter = function(credentials,htmlValidated) {
  if (htmlValidated) {   
    $scope.login(credentials);   
  } 
};
自定义指令ng enter是

.directive('ngEnter', function () { 
 return function (scope, element, attrs) {   
    element.bind("keydown keypress", function (event) {  
           if(event.which === 13) {  
                scope.$apply(function (){    
                    scope.$eval(attrs.ngEnter);  
                 });     
            event.preventDefault();  
            }    
    });  

所有这些的目的是:我希望用户在输入密码并按Enter键时继续登录(这样他就不必在其他地方按单独的登录按钮)。但我还需要验证表单。是否可以更优雅地执行此操作,而不必在按enter键时查询验证函数?

您需要了解一下这一点

它解释了如何在AngularJs中进行表单验证

简单地说,您需要将
输入
标记封装在
表单
标记中,然后您需要使用
表单
标记上的
ng submit
指令,允许用户提交表单而无需点击登录按钮


您不需要使用自定义的
ng enter
指令。

您需要了解一下这一点

它解释了如何在AngularJs中进行表单验证

简单地说,您需要将
输入
标记封装在
表单
标记中,然后您需要使用
表单
标记上的
ng submit
指令,允许用户提交表单而无需点击登录按钮

您不需要使用自定义的
ng enter
指令。

表单提交不需要“ngEnter”或类似的键盘事件处理器。可以在
元素上使用来处理按键(Enter)或按钮单击提交

看法

表单提交不需要“Ncenter”或类似的键盘事件处理器。可以在
元素上使用来处理按键(Enter)或按钮单击提交

看法


请提供一个指向JSFIDLE上代码的工作版本的链接。请提供指向JSFIDLE上代码的工作版本的链接。
<form ng-submit="onLoginSubmit()">
     <input type="text" ng-model="username" />
     <input type="password" ng-model="password" /> 

     <input type="submit" /> 
</form>
function Controller($scope, ...) {

     $scope.onLoginSubmit = function() { 
          if(validate($scope.username, $scope.password)) {
              // Magic 
          }
     }    
}