How to allow 'Open in a new tab' when using ng-click?

All we need is an easy explanation of the problem, so here it is.

I have a table on HTML and each row leads to a different page, with more details about that row. But as I am using angularjs, with ng-click I can’t right click this row and select ‘open in a new tab’. Is there any way to solve it?

Thanks in advance!

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

If possible you should convert your element to an anchor element.

<a ng-href="{{ your dynamic url }}" rel="nofollow noreferrer noopener" ng-click="your function">Your link text</a>

The browser will interpret the element as a link, and will therefor give you the correct dropdown.
Note that you also have to have the correct href value to open in a new tab.

EDIT:
I would recommend this question if you want a more detailed answer on how to fix this kind of behaviour using JQuery.

Method 2

Inside your ng-click function you can call window.open(url, '_blank') however as a word of warning, this will depend on the browser and current settings.

In some cases this will open in a pop-out window and in other cases it will open in a new tab. There is no way to force either behavior as the javascript is browser agnostic, it has simply requested a new window and it is up to the browser the decide how to implement it. see here for a discussion on forcing a tab or window

However the only way to get that right-click option or the ctrl+click to open in a new tab is if the browser sees a <a> tag. Otherwise it doesn’t treat it as a link.

Method 3

If you want to generate your href dynamically based on some condition then you can set your href on ng-mousedown event and after that you can perform any event like open link in new tab, open link in new window and click.

HTML:

<a href="javascript:void(0)" rel="nofollow noreferrer noopener" ng-mousedown="openDetailView($event, userRole)">{{label}}</a>

JS :

  $scope.openDetailView = function (event, userRole) {
         if(userRole == 'admin') {
             jQuery(event.target).attr('href', 'admin/view');

         } else {
             jQuery(event.target).attr('href', 'user/view');

         }
  };

Method 4

You have to use anchor element inside the table row.

HTML

<tr>
    <a ng-href="dynamic url" rel="nofollow noreferrer noopener" ng-click="openItem($event)">Open the item</a>
</tr>

Controller

$scope.openItem = function (event) {
    event.preventDefault();
    // code to open a item
}

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply