0

I have three input elements styled as buttons. On ng-keyup I invoke a function in my controller.

enter image description here

Now the problem is I have to manually click on one of them to get a focus, only then keyUp works.

I tried ng-focus='focus' and then setting $scope.focus=true in controller, it didn't work.

  <div class="row startButtonRow">
    <div class="col col-50" align="center">
      <button class="button button-dark startButton" ng-click="start()" ng-disabled="disableStart">Start</button>
    </div>

    <div class="col" align="center">
      <input ng-focus="focus" type="button" class="button button-dark startButton" ng-disabled="disableStop" ng-keyup="stopTimer($event)">
    </div>

    <div class="col" align="center">
      <input type="button" class="button button-dark startButton" ng-disabled="disableStop" ng-keyup="stopTimer($event)">
    </div>

    <div class="col" align="center">
      <input type="button" class="button button-dark startButton" ng-disabled="disableStop" ng-keyup="stopTimer($event)">
    </div>

  </div>

Once I click Start button the symbols start appearing on three columns and I am supposed to press corresponding button (here input element with key-up) as soon a specific symbol appear. I don't want to click on the element first and then being able to use keyboard keys.

1 Answer 1

1

ng-keyup does not have to go on one of your input elements, you could move it to your body element, or whatever your ng-app element is, and it will still catch keypresses.

On a different note, I believe you are misunderstanding what ng-focus does. It evaluates the given expression when the input is focused, it is not telling your browser to focus that element. You will want to build a custom directive to focus your inputs, see How to set focus on input field?

You could add something like this to your controller:

var handler = function(e){
    if (e.keyCode === 37) {
      // left arrow
    } else if (e.keyCode === 38) {
      // up arrow
    } else if (e.keyCode === 39) {
      // right arrow
    }
};

var $doc = angular.element(document);

$doc.on('keyup', handler);
$scope.$on('$destroy',function(){
  $doc.off('keyup', handler);
})
Sign up to request clarification or add additional context in comments.

2 Comments

I get your first point about ng-keyup, I noticed it when I implemented. Is it possible to press those three buttons with keyboard <-, ^, -> buttons and not mouse click? I didn't find any answer for it, so I went with input and ng-keyup. yes I did mistake with ng-focus, thanks!
Perfect! Thanks a lot!

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.