2014-03-05 55 views
0

我有字段的说明,在我的AngularJS代码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输入是

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

所有这一切的目的:我想用户的登录进行时,他netered密码并按下回车键(所以他不不必在别处按下单独的登录按钮)。但我也需要验证表单。它可以更优雅地完成,而不需要查询验证功能就可以进入?

+0

请提供一个链接上的jsfiddle的代码你的工作版本。 – tomepejo

回答

3

你需要看看这个article

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

简单地说,你需要附上form标签内的input标签,然后你需要使用ng-submit指令的form标签允许用户提交表单没有击中登录按钮。

您不需要使用您的定制ng-enter指令。

1

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

查看

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