0

I am using AngularJS in my application and I want to use combination Ctrl+N to go to state and view responsible for creating new objects in my application. The problem is that this combination opens a new windows in my internet browser.

The question is: is it possible to prevent this combination and use it to go to a new view in my app?

I know about ng-keyup directive, what's more I can catch single keys like Shift or Ctrl, but I would like to catch combination Ctrl+N and go to a new view.

Right now I have following code:

HTML:

ng-keyup="keyPress($event)

Angular:

$scope.keyPress = function(e) {
    e.preventDefault();
    if (e.ctrlKey) {
        var i = 2;
    }   
};

Unfortunately method preventDefault() doesn't work, and pressing Ctrl+N still opens a new window.

Andrii Omelchenko
  • 13,183
  • 12
  • 43
  • 79
TheOpti
  • 1,641
  • 3
  • 21
  • 38

1 Answers1

2

I think you can use preventDefault() at this point. The character n should be the keycode 78

 $(document).keydown(function (objEvent) {
  if (objEvent.ctrlKey && objEvent.keyCode== 78) {
   objEvent.preventDefault();

   ...
 });

edit

Pascal
  • 122
  • 5
  • still does not work - it doesn't see property "Ctrl" as true even though keyCode is equal 17. – TheOpti Oct 14 '14 at 09:44
  • http://stackoverflow.com/questions/7295508/javascript-capture-browser-shortcuts-ctrlt-n-w try your luck here :) – Pascal Oct 14 '14 at 09:52
  • I've already seen it. The problem is that javascript catches ctrl or other key - only one at a time. So these conditions in if-else statement are always false and do not work for me. – TheOpti Oct 14 '14 at 09:56
  • OK, it works only for some combinations (for example: CTRL + '+'). Unfortunately it doesn't work for CTRL + N... – TheOpti Oct 14 '14 at 10:51
  • which browser you are using? – Pascal Oct 14 '14 at 10:56
  • Did you already try to change the event from Keypress to Keydown or Keyup? There is a similar problem: http://stackoverflow.com/questions/11000826/ctrls-preventdefault-in-chrome – Pascal Oct 14 '14 at 11:27