如何在AngularJS中使用按键事件?

我想捕捉下面文本框上的回车键事件。为了更清楚地说明,我使用ng-repeat填充tbody。下面是HTML:

<td><input type="number" id="closeqty{{$index}}" class="pagination-right closefield"
data-ng-model="closeqtymodel" data-ng-change="change($index)" required placeholder="{{item.closeMeasure}}" /></td>

这是我的模块:

angular.module('components', ['ngResource']);

我使用一个资源来填充表,我的控制器代码是:

function Ajaxy($scope, $resource) {
//controller which has resource to populate the table
}
503774 次浏览

你需要添加一个directive,像这样:

Javascript:

app.directive('myEnter', function () {
return function (scope, element, attrs) {
element.bind("keydown keypress", function (event) {
if(event.which === 13) {
scope.$apply(function (){
scope.$eval(attrs.myEnter);
});


event.preventDefault();
}
});
};
});

超文本标记语言:

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

另一种方法是使用标准指令ng-keypress="myFunct($event)"

然后在你的控制器中你可以有:

...


$scope.myFunct = function(keyEvent) {
if (keyEvent.which === 13)
alert('I am an alert');
}


...
我为我的项目所做的一些代码示例。 基本上你向你的实体添加标签。 想象一下你有输入文本,在输入标签名称时,你会得到一个带有预加载标签的下拉菜单,你可以用箭头导航,然后用Enter选择:

HTML + AngularJS v1.2.0-rc.3

    <div>
<form ng-submit="addTag(newTag)">
<input id="newTag" ng-model="newTag" type="text" class="form-control" placeholder="Enter new tag"
style="padding-left: 10px; width: 700px; height: 33px; margin-top: 10px; margin-bottom: 3px;" autofocus
data-toggle="dropdown"
ng-change="preloadTags()"
ng-keydown="navigateTags($event)">
<div ng-show="preloadedTags.length > 0">
<nav class="dropdown">
<div class="dropdown-menu preloadedTagPanel">
<div ng-repeat="preloadedTag in preloadedTags"
class="preloadedTagItemPanel"
ng-class="preloadedTag.activeTag ? 'preloadedTagItemPanelActive' : '' "
ng-click="selectTag(preloadedTag)"
tabindex="\{\{ $index }}">
<a class="preloadedTagItem"
ng-class="preloadedTag.activeTag ? 'preloadedTagItemActive' : '' "
ng-click="selectTag(preloadedTag)">\{\{ preloadedTag.label }}</a>
</div>
</div>
</nav>
</div>
</form>
</div>

Controller.js

$scope.preloadTags = function () {
var newTag = $scope.newTag;
if (newTag && newTag.trim()) {
newTag = newTag.trim().toLowerCase();


$http(
{
method: 'GET',
url: 'api/tag/gettags',
dataType: 'json',
contentType: 'application/json',
mimeType: 'application/json',
params: {'term': newTag}
}
)
.success(function (result) {
$scope.preloadedTags = result;
$scope.preloadedTagsIndex = -1;
}
)
.error(function (data, status, headers, config) {
}
);
} else {
$scope.preloadedTags = {};
$scope.preloadedTagsIndex = -1;
}
};


function checkIndex(index) {
if (index > $scope.preloadedTags.length - 1) {
return 0;
}
if (index < 0) {
return $scope.preloadedTags.length - 1;
}
return index;
}


function removeAllActiveTags() {
for (var x = 0; x < $scope.preloadedTags.length; x++) {
if ($scope.preloadedTags[x].activeTag) {
$scope.preloadedTags[x].activeTag = false;
}
}
}


$scope.navigateTags = function ($event) {
if (!$scope.newTag || $scope.preloadedTags.length == 0) {
return;
}
if ($event.keyCode == 40) {  // down
removeAllActiveTags();
$scope.preloadedTagsIndex = checkIndex($scope.preloadedTagsIndex + 1);
$scope.preloadedTags[$scope.preloadedTagsIndex].activeTag = true;
} else if ($event.keyCode == 38) {  // up
removeAllActiveTags();
$scope.preloadedTagsIndex = checkIndex($scope.preloadedTagsIndex - 1);
$scope.preloadedTags[$scope.preloadedTagsIndex].activeTag = true;
} else if ($event.keyCode == 13) {  // enter
removeAllActiveTags();
$scope.selectTag($scope.preloadedTags[$scope.preloadedTagsIndex]);
}
};


$scope.selectTag = function (preloadedTag) {
$scope.addTag(preloadedTag.label);
};

CSS + Bootstrap v2.3.2

.preloadedTagPanel {
background-color: #FFFFFF;
display: block;
min-width: 250px;
max-width: 700px;
border: 1px solid #666666;
padding-top: 0;
border-radius: 0;
}


.preloadedTagItemPanel {
background-color: #FFFFFF;
border-bottom: 1px solid #666666;
cursor: pointer;
}


.preloadedTagItemPanel:hover {
background-color: #666666;
}


.preloadedTagItemPanelActive {
background-color: #666666;
}


.preloadedTagItem {
display: inline-block;
text-decoration: none;
margin-left: 5px;
margin-right: 5px;
padding-top: 5px;
padding-bottom: 5px;
padding-left: 20px;
padding-right: 10px;
color: #666666 !important;
font-size: 11px;
}


.preloadedTagItem:hover {
background-color: #666666;
}


.preloadedTagItemActive {
background-color: #666666;
color: #FFFFFF !important;
}


.dropdown .preloadedTagItemPanel:last-child {
border-bottom: 0;
}

你也可以把它应用到父元素的控制器上。此示例可用于通过按上下方向键突出显示表中的一行。

app.controller('tableCtrl', [ '$scope', '$element', function($scope, $element) {
$scope.index = 0; // row index
$scope.data = []; // array of items
$scope.keypress = function(offset) {
console.log('keypress', offset);
var i = $scope.index + offset;
if (i < 0) { i = $scope.data.length - 1; }
if (i >= $scope.data.length) { i = 0; }
};
$element.bind("keydown keypress", function (event) {
console.log('keypress', event, event.which);
if(event.which === 38) { // up
$scope.keypress(-1);
} else if (event.which === 40) { // down
$scope.keypress(1);
} else {
return;
}
event.preventDefault();
});
}]);




<table class="table table-striped" ng-controller="tableCtrl">
<thead>
<tr>
<th ng-repeat="(key, value) in data[0]">\{\{key}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in data track by $index" ng-click="draw($index)" ng-class="$index == index ? 'info' : ''">
<td ng-repeat="(key, value) in row">\{\{value}}</td>
</tr>
</tbody>
</table>

另一个简单的选择:

<input ng-model="edItem" type="text"
ng-keypress="($event.which === 13)?foo(edItem):0"/>

ng-ui的替代品:

<input ng-model="edItem" type="text" ui-keypress="{'enter':'foo(edItem)'}"/>

我有点晚了。但我发现了一个更简单的解决方案使用auto-focus ..当弹出dialog对象时,这对于按钮或其他对象很有用:

<button auto-focus ng-click="func()">ok</button>

如果你想按onSpace或Enter按钮,这应该没问题。

尝试

ng-keypress="console.log($event)"
ng-keypress="alert(123)"

什么也没为我做。

Strangley在https://docs.angularjs.org/api/ng/directive/ngKeypress的示例中,执行ng-keypress="count = count + 1",工作正常。

我找到了一个替代的解决方案,它有按Enter调用按钮的ng-click。

<input ng-model="..." onkeypress="if (event.which==13) document.getElementById('button').click()"/>
<button id="button" ng-click="doSomething()">Done</button>

这是对EpokK答案的扩展。

我有同样的问题,必须调用一个作用域函数时,enter被推到一个输入字段。然而,我也想将的值传递给指定的函数。这是我的解决方案:

app.directive('ltaEnter', function () {
return function (scope, element, attrs) {
element.bind("keydown keypress", function (event) {
if(event.which === 13) {
// Create closure with proper command
var fn = function(command) {
var cmd = command;
return function() {
scope.$eval(cmd);
};
}(attrs.ltaEnter.replace('()', '("'+ event.target.value +'")' ));


// Apply function
scope.$apply(fn);


event.preventDefault();
}
});
};

});

在HTML中的用法如下:

<input type="text" name="itemname" lta-enter="add()" placeholder="Add item"/>

向EpokK的回答致敬。

我最简单的方法是使用angular内置指令:

ng-keypressng-keydownng-keyup

通常,我们希望为已经由ng-click处理的内容添加键盘支持。

例如:

<a ng-click="action()">action</a>

现在,让我们添加键盘支持。

由回车键触发:

<a ng-click="action()"
ng-keydown="$event.keyCode === 13 && action()">action</a>

空格键:

<a ng-click="action()"
ng-keydown="$event.keyCode === 32 && action()">action</a>

空格或输入键:

<a ng-click="action()"
ng-keydown="($event.keyCode === 13 || $event.keyCode === 32) && action()">action</a>

如果你使用的是现代浏览器

<a ng-click="action()"
ng-keydown="[13, 32].includes($event.keyCode) && action()">action</a>

更多关于keyCode:
keyCode已弃用,但支持良好的API,你可以使用$ eventt。请输入受支持的浏览器 详见https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key

下面是我在构建一个具有类似需求的应用程序时得出的结论, 它不需要写一个指令,它相对简单地告诉它做什么:

<input type="text" ng-keypress="($event.charCode==13)?myFunction():return" placeholder="Will Submit on Enter">

这个呢?:

<form ng-submit="chat.sendMessage()">
<input type="text" />
<button type="submit">
</form>

现在,当你在输入后按回车键时,表单知道如何处理它。

你可以使用ng-keydown ="myFunction($event)"作为属性

<input ng-keydown="myFunction($event)" type="number">


myFunction(event) {
if(event.keyCode == 13) {   // '13' is the key code for enter
// do what you want to do when 'enter' is pressed :)
}
}

这是我的指示:

mainApp.directive('number', function () {
return {
link: function (scope, el, attr) {
el.bind("keydown keypress", function (event) {
//ignore all characters that are not numbers, except backspace, delete, left arrow and right arrow
if ((event.keyCode < 48 || event.keyCode > 57) && event.keyCode != 8 && event.keyCode != 46 && event.keyCode != 37 && event.keyCode != 39) {
event.preventDefault();
}
});
}
};
});

用法:

<input number />

你可以使用ng-keydown, ng-keyup, ng-press,像这样。

触发一个函数:

   <input type="text" ng-keypress="function()"/>

或者如果你有一个条件,比如当他按下escape(27是键 转义代码)

 <form ng-keydown=" event.which=== 27?cancelSplit():0">
....
</form>

超文本标记语言

<textarea id="messageTxt"
rows="5"
placeholder="Escriba su mensaje"
ng-keypress="keyPressed($event)"
ng-model="smsData.mensaje">
</textarea>

controller.js

$scope.keyPressed = function (keyEvent) {
if (keyEvent.keyCode == 13) {
alert('presiono enter');
console.log('presiono enter');
}
};

我认为使用文档。Bind更优雅一些

constructor($scope, $document) {
var that = this;
$document.bind("keydown", function(event) {
$scope.$apply(function(){
that.handleKeyDown(event);
});
});
}

获取文档到控制器构造函数:

controller: ['$scope', '$document', MyCtrl]
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
Informe your name:<input type="text" ng-model="pergunta" ng-keypress="pressionou_enter($event)" ></input>
<button ng-click="chamar()">submit</button>
<h1>\{\{resposta}}</h1>
</div>
<script>
var app = angular.module('myApp', []);
//create a service mitsuplik
app.service('mitsuplik', function() {
this.myFunc = function (parametro) {
var tmp = "";
for (var x=0;x<parametro.length;x++)
{
tmp = parametro.substring(x,x+1) + tmp;
}
return tmp;
}
});
//Calling our service
app.controller('myCtrl', function($scope, mitsuplik) {
$scope.chamar = function() {
$scope.resposta = mitsuplik.myFunc($scope.pergunta);
};
//if mitsuplik press [ENTER], execute too
$scope.pressionou_enter = function(keyEvent) {
if (keyEvent.which === 13)
{
$scope.chamar();
}


}
});
</script>
</body>
</html>
(function(angular) {
'use strict';
angular.module('dragModule', [])
.directive('myDraggable', ['$document', function($document) {
return {
link: function(scope, element, attr) {
element.bind("keydown keypress", function (event) {
console.log('keydown keypress', event.which);
if(event.which === 13) {
event.preventDefault();
}
});
}
};
}]);
})(window.angular);

所有你需要做的事情是获得事件如下:

console.log(angular.element(event.which));

一个指令可以做它,但不是你如何做它。