2

ng-click and ng-href directives when used together will first execute click function. In the following example navigation to Google will be prevented and alert will be shown.

<a ng-href='http://google.com' ng-click="click($event)">Link</a>

$scope.click = function (event) {
    event.preventDefault();
    alert('click has been trigerred');
}

This will work though only when user clicks a link using left mouse button. If user will try to open the link in a new tab the click event won't be triggered. To some extent it seems correct because it's not strictly speaking "click", but is there any Angular directive for handling opening link in the new tab?

UPDATE:

I don't want to open new tab programatically, but handle event of opening new tab by the user.

Arkadiusz Kałkus
  • 17,101
  • 19
  • 69
  • 108
  • If you want prevent right click, you need to override the default context menu behaviour. Maybe this can help http://stackoverflow.com/questions/15731634/how-do-i-handle-right-click-events-in-angular-js – Nico Vignola Jul 15 '16 at 13:42
  • @Stuff_H4pp3nz I'm sorry for vagueness of my question. I want to handle event of opening new tab by the user, not prevent it. – Arkadiusz Kałkus Jul 15 '16 at 13:49
  • Hi @Landeeyo, were you able to solve this in the end? I'm facing the same dilemma. I want the user to be able to decide whether he wants to click or rmc and open new tab. – Starceaker Feb 24 '17 at 16:19
  • 1
    Hi @Starceaker. I'm sorry, but as far as I remember I didn't solve it. – Arkadiusz Kałkus Feb 24 '17 at 16:25

1 Answers1

1

Instead of using ng-href you could use one more function on click which will open the new tab for you.

<a  ng-click="openTab(); click($event)">Link</a>

$scope.click = function (event) {
    event.preventDefault();
    alert('click has been trigerred');
}
$scope.openTab() {
    $window.open('https://www.google.com', '_blank');
}
Sumit Chaudhari
  • 210
  • 1
  • 15