我想捕捉下面文本框上的回车键事件。为了更清楚地说明这一点,我使用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
}
尝试
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>
你需要添加一个指令,像这样:
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();
}
});
};
});
HTML:
<div ng-app="" ng-controller="MainCtrl">
<input type="text" my-enter="doSomething()">
</div>
尝试
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>
(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);
这是我的指示:
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 />