1

while in console we see that it changed? http://jsfiddle.net/LCZfd/1006/

app.controller("myCtrl", function($document) {
    let scope=this;
    this.current=0;

    this.isCurrent=function(val){
        return val==this.current;
    }
    this.selectCurrent=function(val){
        this.current=val;
    }
    $document.on('keypress', keyupHandler);
    function keyupHandler(keyEvent) {
        scope.selectCurrent(keyEvent.key-1);
        console.log(scope.current);
    } 
});

Open the console and you will see that variable changed its value. I just want to use keyboard in my app.

8
  • what are you trying to achieve with this scope.selectCurrent(keyEvent.key-1); key is a property which returns a alphabet and you are subtracting 1 from it???? Commented Aug 28, 2017 at 15:05
  • Little trouble here return val==this.current;, the this on this context belongs the function isCurrent not the controller it self, you may use your cached variable scope like return val == scope.current; instead. Commented Aug 28, 2017 at 15:08
  • your code seem to produce a warning about the module, maybe that's a reason it doesn't work Commented Aug 28, 2017 at 15:23
  • On your first line you set a named reference to this but then you don't use it. Try replacing all your references to this with the named reference. By the way, 'scope' is not a good idea for the named reference to this in this context because this is actually your controller instance. Name it 'ctrl' or 'myCtrl' or something that won't cause it to be confused with a proper AngularJS scope object. Commented Aug 28, 2017 at 15:30
  • Also, you are trying to subtract a number from keyEvent.key but that property is not numeric, so you're assigning NaN to your current property. Commented Aug 28, 2017 at 15:33

1 Answer 1

1

this is quite simple but i had forgotten that. If you use events that are external to angular's refresh cycle, it's not applied. This will work like this, but it's not recommended, because if you try to apply while in a digesting cycle, this will cause an error. You should read the docs to find a solution to stay in the borders of angular:

app.controller("myCtrl", function($document, $rootScope) {
    let scope=this;
    this.current=0;

    this.isCurrent=function(val){
        return val==this.current;
    }
    this.selectCurrent=function(val){
        this.current=val;
    }
    $document.on('keypress', keyupHandler);
    function keyupHandler(keyEvent) {
        //the apply:
        $rootScope.$apply(scope.selectCurrent(keyEvent.key-1));
        console.log(scope.current);
    } 
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.