AngualrJs提供了ng-keyup, ng-keydown, ng-keypress
可以用來偵測按鍵事件。
<div ng-controller="MyCtrl">
<input.search-input ng-keydown="onSearchKeyDown($event)">
</div>
angular.module("exApp").controller("MyCtrl", function ($scope)
{
$scope.onSearchKeyDown = function (event) {
# do something ...
$scope.key = event.keyCode
};
}
注意AngularJS的event會被傳遞至上層的DOM,例如:
<div ng-controller="MyCtrl">
<div.menu-panel ng-keydown="onMenuKeyDown($event)">
<input.search-input ng-keydown="onSearchKeyDown($event)">
</div>
</div>
angular.module("exApp").controller("MyCtrl", function ($scope)
{
$scope.onMenuKeyDown = function (event) {
$scope.keyMenu = event.keyCode
};
$scope.onSearchKeyDown = function (event) {
$scope.keySearch = event.keyCode
};
}
這時可以加上event.stopPropagation();
來停止事件的傳遞。
angular.module("exApp").controller("MyCtrl", function ($scope)
{
$scope.onMenuKeyDown = function (event) {
$scope.keyMenu = event.keyCode
};
$scope.onSearchKeyDown = function (event) {
$scope.keySearch = event.keyCode
event.stopPropagation();
};
}