zoukankan      html  css  js  c++  java
  • Submit form on pressing Enter with AngularJS

    原文地址:http://stackoverflow.com/questions/15417125/submit-form-on-pressing-enter-with-angularjs

    方案1:

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

    Javascript:

    angular.module('yourModuleName').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': event});
                        });
    
                        event.preventDefault();
                    }
                });
            };
        });

    HTML:

    <div ng-app="" ng-controller="MainCtrl">
        <input type="text" ng-enter="doSomething()">    
    </div>

    方案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 way to the built-in ngClass:

    HTML

    <input key-bind="{ enter: 'go()', esc: 'clear()' }" type="text"></input>

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

    So for example: esc : 'clear()' instead of esc : 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) {
            function map(obj) {
                var mapped = {};
                for (var key in obj) {
                    var action = obj[key];
                    if (keyCodes.hasOwnProperty(key)) {
                        mapped[keyCodes[key]] = action;
                    }
                }
                return mapped;
            }
    
            return function (scope, element, attrs) {
                var bindings = map(scope.$eval(attrs.keyBind));
                element.bind("keydown keypress", function (event) {
                    if (bindings.hasOwnProperty(event.which)) {
                        scope.$apply(function() {
                             scope.$eval(bindings[event.which]);
                        });
                    }
                });
            };
        }]);
  • 相关阅读:
    二阶注入
    ACCESS延时注入
    宽字节注入源码
    Sqli-LABS通关笔录-14
    Sqli-LABS通关笔录-13
    Sqli-LABS通关笔录-12
    PHP学习路线
    华科机考:二叉排序树
    华科机考:打印日期
    华科机考:A+B
  • 原文地址:https://www.cnblogs.com/uncleJOKER/p/5522682.html
Copyright © 2011-2022 走看看