天天看点

使用AngularJS按Enter键提交表单

本文翻译自:Submit form on pressing Enter with AngularJS

In this particular case, what options do I have to make these inputs call a function when I press Enter?

在这种特殊情况下,当我按Enter键时,我有什么选项可以使这些输入调用一个函数?
// HTML view //
<form>
    <input type="text" ng-model="name" <!-- Press ENTER and call myFunc --> />
    <br />
    <input type="text" ng-model="email" <!-- Press ENTER and call myFunc --> />
</form>

// Controller //
.controller('mycontroller', ['$scope',function($scope) {
    $scope.name = '';
    $scope.email = '';
    // Function to be called when pressing ENTER
    $scope.myFunc = function() {
       alert('Submitted');
    };
}])
           

#1楼

参考:https://stackoom.com/question/12ghJ/使用AngularJS按Enter键提交表单

#2楼

Angular supports this out of the box.

Angular支持开箱即用。

Have you tried ngSubmit on your form element?

你在表单元素上尝试过ngSubmit吗?
<form ng-submit="myFunc()" ng-controller="mycontroller">
   <input type="text" ng-model="name" />
    <br />
    <input type="text" ng-model="email" />
</form>
           

EDIT: Per the comment regarding the submit button, see Submitting a form by pressing enter without a submit button which gives the solution of:

编辑:根据有关提交按钮的注释,请参阅提交表单,按Enter键而不提交按钮 ,该按钮提供以下解决方案:
<input type="submit" style="position: absolute; left: -9999px; width: 1px; height: 1px;"/>
           

If you don't like the hidden submit button solution, you'll need to bind a controller function to the Enter keypress or keyup event.

如果您不喜欢隐藏的提交按钮解决方案,则需要将控制器功能绑定到Enter键或键盘事件。

This normally requires a custom directive, but the AngularUI library has a nice keypress solution set up already.

这通常需要一个自定义指令,但AngularUI库已经设置了一个很好的keypress解决方案。

See http://angular-ui.github.com/

见http://angular-ui.github.com/

After adding the angularUI lib, your code would be something like:

添加angularUI lib后,您的代码将类似于:
<form ui-keypress="{13:'myFunc($event)'}">
  ... input fields ...
</form>
           

or you can bind the enter keypress to each individual field.

或者您可以将Enter键压缩到每个单独的字段。

Also, see this SO questions for creating a simple keypres directive: How can I detect onKeyUp in AngularJS?

另外,请参阅此SO问题以创建简单的keypres指令: 如何在AngularJS中检测onKeyUp?

EDIT (2014-08-28): At the time this answer was written, ng-keypress/ng-keyup/ng-keydown did not exist as native directives in AngularJS.

编辑(2014-08-28):在撰写本答案时,ng-keypress / ng-keyup / ng-keydown在AngularJS中不作为本机指令存在。

In the comments below @darlan-alves has a pretty good solution with:

在下面的评论中,@ darlan-alves有一个非常好的解决方案:

<input ng-keyup="$event.keyCode == 13 && myFunc()"... />

#3楼

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

如果要在没有表单的情况下调用函数,可以使用我的ngEnter指令:

Javascript :

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 :

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

I submit others awesome directives on my twitter and my gist account .

我在twitter和我的gist帐户上提交了其他令人敬畏的指令。

#4楼

If you only have one input you can use the form tag.

如果您只有一个输入,则可以使用表单标记。
<form ng-submit="myFunc()" ...>
           

If you have more than one input, or don't want to use the form tag, or want to attach the enter-key functionality to a specific field, you can inline it to a specific input as follows:

如果您有多个输入,或者不想使用表单标记,或者想要将回车键功能附加到特定字段,则可以将其内联到特定输入,如下所示:
<input ng-keyup="$event.keyCode == 13 && myFunc()" ...>
           

#5楼

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

:

我想要一些比给定答案更具可扩展性/语义性的东西,所以我写了一个指令,它采用与内置

ngClass

类似的方式获取javascript对象:

HTML 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()

例如:

esc : 'clear()'

而不是

esc : clear()

Javascript 使用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]);
                    });
                }
            });
        };
    }]);
           

#6楼

Will be slightly neater using a CSS class instead of repeating inline styles.

使用CSS类而不是重复内联样式会稍微整洁一些。

CSS

CSS
input[type=submit] {
    position: absolute;
    left: -9999px;
}
           

HTML

HTML
<form ng-submit="myFunc()">
    <input type="text" ng-model="name" />
    <br />
    <input type="text" ng-model="email" />
    <input type="submit" />
</form>
           

继续阅读