I have to make hotkay for my page on AngularJS. I use document.addEventListener()
Method keyDownTextField() sets value wordToShow:
export class listenKey {
constructor() {
document.addEventListener("keydown", (e) => this.keyDownTextField(e), false);
}
keyDownTextField(e: any) {
var keyCode = e.keyCode;
this.logKey(keyCode);
this.wordToShow = "Hello world!";
}
logKey(key: any) {
console.log( key );
}
}
There is the template:
<div ng-click="$ctrl.logKey()" ng-bind="$ctrl.wordToShow"></div>
The problem is: ng-bind works when the div is clicked but don't works when addEventListener registers that the key is pressed. How to solve it?
This looks like a support question;
Please use one of the support channels for help: https://github.com/angular/angular.js/blob/master/CONTRIBUTING.md#question
Github issues are for bug reports.
document.addEventListener
doesn't trigger angularjs' change detection system (so AngularJS isn't aware of the click and is unable to represent the correct state).
It's a good idea to avoid using event listener that exist outside of angularjs.
If you do have the need for this, you probably want to manually trigger the digest. But you shouldn't. Instead, stick met the ng-click
.
The "key" to solving this is to call $rootScope.$apply()
inside your hotkey handler.
Closing as this is a support question and not an issue with AngularJS.
(thanks @frederikprijck)
Most helpful comment
The "key" to solving this is to call
$rootScope.$apply()
inside your hotkey handler.Closing as this is a support question and not an issue with AngularJS.
(thanks @frederikprijck)