我想捕捉下面文本框上的回车键事件。为了更清楚地说明这一点,我使用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
}
我最简单的方法是使用angular内置指令:
ngk, ngk或ngke是的。
通常,我们希望为已经由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
<!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);