Submit form on pressing Enter with AngularJS

Source: Internet
Author: User
Tags hasownproperty

Original address: Http://stackoverflow.com/questions/15417125/submit-form-on-pressing-enter-with-angularjs

Scenario 1:

If you want to call function without form you can use my ngenter directive:

Javascript:

function () {        returnfunction(scope, element, attrs) {            element.bind (function  (event) {                if(Event.which = = =) {                    scope. $apply (function () {                        scope. $eval (Attrs.ngenter, {' event ': Event});                    });                    Event.preventdefault ();     });

HTML:

<ng-app= ""  ng-controller= "Mainctrl">     <type= "text"  ng-enter= "dosomething ()">     </div>

Scenario 2:

I wanted something a little more extensible/semantic than the given answers so I wrote a directive that takes a JavaScript Object in a similar the built-in ngClass :

Html
<key-bind= "{enter: ' Go () ', ESC: ' Clear () '}"  type= "text"  ></input>

The values of the object is evaluated in the context of the directive ' s scope-ensure they is encased in single quotes Otherwise all of the functions would be executed when the directive is loaded (!)

So for example: esc : ‘clear()‘ instead ofesc : clear()

Javascript
MyModule. Constant (' Keycodes ', {ESC:27, Space:32, enter:13, Tab:9, BACKSPACE:8, Shift:16, Ctrl:17, alt:18, CapsLock:20, NumLock:144}). directive (' Keybind ', [' keycodes ',function(keycodes) {functionMap (obj) {varMapped = {};  for(varKeyinchobj) {                varAction =Obj[key]; if(Keycodes.hasownproperty (key)) {Mapped[keycodes[key]]=Action; }            }            returnmapped; }        return function(scope, element, Attrs) {varBindings =map (scope. $eval (Attrs.keybind)); Element.bind ("KeyDown keypress",function(event) {if(Bindings.hasownproperty (Event.which)) {scope. $apply (function() {scope. $eval (Bindings[event.which]);                });        }            });    }; }]);

Submit form on pressing Enter with AngularJS

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.