Angular.js: document.addEventListener() doesn't work with ng-bind

Created on 12 Dec 2017  路  2Comments  路  Source: angular/angular.js

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?

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)

All 2 comments

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)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

guruward picture guruward  路  145Comments

leeola picture leeola  路  76Comments

georgiosd picture georgiosd  路  124Comments

cgross picture cgross  路  194Comments

coli picture coli  路  62Comments