Jordash
Jordash

Reputation: 3103

Bind Hotkey to button click in Angular

I have a div which has an ng-click event:

<div class="modalWindowClose" ng-click="closeSettings(user, users);"><i class="fa fa-times"></i></div>

I want to click the element when the escape key is pressed, preferably within the HTML itself. Something like this:

<div class="modalWindowClose" hotkey="{esc:'click this element'}" ng-click="closeSettings(user, users);"><i class="fa fa-times"></i></div>

What is the best way to do something like that? I tried the Angular hotkeys by Chief Fancy Pants but it didn't let me click the specific element, only run a function.

Upvotes: 1

Views: 2387

Answers (2)

dfsq
dfsq

Reputation: 193311

As I said in comments, you should probably write custom hotkey directive. I would design the simple one like this:

.directive('hotkey', function() {
  return {
    link: function(scope, element, attrs) {
      var config = scope.$eval(attrs.hotkey)
      angular.forEach(config, function(value, key) {
        angular.element(window).on('keydown', function(e) {
          if (e.keyCode === Number(key)) {
            element.triggerHandler(value)  
          }
        })
      })
    }
  }
})

Then it would be used in HTML like this:

<div hotkey="{27: 'click'}" ng-click="closeSettings(user, users);">Close</div>

Where "27" is the key code (27 is ESC) and the value click corresponds to the action to trigger on this element.

Check out the usage and demo of it in action below.

angular.module('demo', [])

.controller('DemoController', function($scope) {
  $scope.closeSettings = function() {
    console.log('closeSettings')
  }
})

.directive('hotkey', function() {
  return {
    link: function(scope, element, attrs) {
      var config = scope.$eval(attrs.hotkey)
      angular.forEach(config, function(value, key) {
        angular.element(window).on('keydown', function(e) {
          if (e.keyCode === Number(key)) {
            element.triggerHandler(value)  
          }
        })
      })
    }
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>

<div ng-app="demo" ng-controller="DemoController">
  <div class="modalWindowClose" hotkey="{27: 'click'}" ng-click="closeSettings(user, users);"><i class="fa fa-times"></i> Close</div>
</div>

Upvotes: 2

Jordi Ruiz
Jordi Ruiz

Reputation: 487

You can use ng-keypress directive and then check the keyEvent in your controller.

You can find more documentation here:

https://docs.angularjs.org/api/ng/directive/ngKeypress

<div ng-keypress="test(param1, $event)" ng-click="test(param1)></div>

$scope.test = function(param1, keyEvent) {
  if(keyEvent) {
    if(keyEvent.which === 23) { 
       // esc
    }
  } else {
       // click
  }

};

Upvotes: 1

Related Questions