JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
<div ng-controller="MainCtrl">{{ hello }}</div>
JavaScript
var app = angular.module('myApp', []);
app.controller('MainCtrl', ['$scope', '$rootScope', function ($scope, $rootScope) {
$scope.hello = "Hello World";
var count = 0;
$scope.hideOverlays = function () {
count++;
console.log('Hi');
$scope.safeApply(function () {
$scope.hello = "You pressed the escape key " + count + " times.";
});
};
$rootScope.$on('keydown-escape', $scope.hideOverlays);
$scope.safeApply = function (fn) {
var phase = this.$root.$$phase;
if (phase == '$apply' || phase == '$digest') {
if (fn && (typeof (fn) === 'function')) {
fn();
}
} else {
this.$apply(fn);
}
};
}]);
var keycodes = {
'escape': 27,
}
app.run(function ($rootScope, $window) {
angular.element($window).on('keydown', function (e) {
for (var name in keycodes) {
if (e.keyCode === keycodes[name]) {
$rootScope.$broadcast('keydown-' + name, angular.element(e.target))
}
}
})
});