0

I have a description of field in my AngularJS code:

    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)

The line in question is ng-enter one. The function loginByEnter is:

$scope.loginByEnter = function(credentials,htmlValidated) {
  if (htmlValidated) {   
    $scope.login(credentials);   
  } 
};

And custom directive ng-enter is

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

The purpose of all this: I want user to proceed with login when he netered password and hit Enter (so he does not have to press separate Login button elsewhere). But I also need to validate the form. Can it be done more elegantly, without querying a validation function on hitting enter?

1
  • Please provide a link to your working version of the code on JSFiddle. Commented Mar 5, 2014 at 16:12

2 Answers 2

3

You need to take a look at this article.

It explains how you can do form validation in AngularJs.

Simply put, you need to enclose the input tag inside a form tag and then you need to use the ng-submit directive on the form tag to allow the user to submit the form without hitting the login button.

You don't need to make use of your custom ng-enter directive.

Sign up to request clarification or add additional context in comments.

Comments

1

"ngEnter" or similar keyboard event processors are not needed for form submission. One can use ngSubmit on <form> elements to handle either key press (Enter) or button click submission.

View

<form ng-submit="onLoginSubmit()">
     <input type="text" ng-model="username" />
     <input type="password" ng-model="password" /> 

     <input type="submit" /> 
</form>

Controller

function Controller($scope, ...) {

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.