Nitish Nitish - 4 months ago 53
AngularJS Question

angular ng-focus / focus input element

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.

Answer

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);
})