Saturday, 24 May 2014

Submit form on enter click – Angular js

It is very easy to achieve this in angular js .We can check with one example. Suppose you have one text box inside the form and want to submit on enter key here is the way.

 

<form name="name" class="form" ng-submit="submitform()">

 <input type="text" ng-model="model.term"/>
 
 <button type="submit" class="btn">
  Submit
 </button>

</form>


What we have done is that just defined our function in ng-submit. It will work perfectly but there are some situations we have to deal with multiple text box and have to submit on enter .In that case you can define simple directive and you can add your function on ng-enter .

Lets check with another example .

 

<input type="text" ng-enter="submifunction1();" ng-model="model.term1"/>

<input type="text" ng-enter="submifunction2();" ng-model="model.term2"/>

<input type="text" ng-enter="submifunction3();" ng-model="model.term3"/>
 

Directive

 

angular.module('yourmodule').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();
            }
        });
    };
});

 

Related Posts

1. Angular routing

2. Rating Stars using angular js Directive concept

3. Communication between factory file and controller in Angular js

4. Communicate with controllers in angular js

5.Client side pagination using angular js


7 comments :

  1. ng-keypress with $event.keyCode == 13

    ReplyDelete
  2. Hey Prashobh,
    This solution works perfect.
    But there is one problem.
    I have a form, and inside this form I have many input fields. I just want to give enter submit to only one text field. When I used this directive to just one text field and tried to submit with another text field then also it works. How to get rid of this?
    Thanks in advance.

    ReplyDelete
  3. Hi,

    It worked for me.
    Thanks for the directive.

    Regards,
    Shashikiran

    ReplyDelete
  4. Final thoughts: Very cute and effectively made.

    ReplyDelete
  5. It worked for me too.
    Thanks for this code!

    ReplyDelete
  6. Hello there, You've done an excellent job. I will certainly digg it and in my view suggest to my friends.
    I'm confident they will be benefited from this website.

    ReplyDelete