我想应该使用伪指令,但是将伪指令添加到正文中却侦听文档中的事件似乎很奇怪。
什么是正确的方法?
更新:找到了AngularJSUI,并看到了它们对keypress指令的实现。
这就是我使用jQuery完成此操作的方式-我认为有更好的方法。
var app = angular.module('angularjs-starter', []); app.directive('shortcut', function() { return { restrict: 'E', replace: true, scope: true, link: function postLink(scope, iElement, iAttrs){ jQuery(document).on('keypress', function(e){ scope.$apply(scope.keyPressed(e)); }); } }; }); app.controller('MainCtrl', function($scope) { $scope.name = 'World'; $scope.keyCode = ""; $scope.keyPressed = function(e) { $scope.keyCode = e.which; }; }); <body ng-controller="MainCtrl"> <shortcut></shortcut> <h1>View keys pressed</h1> {{keyCode}} </body>
plnkr演示