Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally add target="_blank" to links with Angular JS

I am building a navigation tree in Angular JS. Most links in the tree will point to pages within my website, but some may point to external sites.

If the href of a link begins with http:// or https:// then I am assuming the link is for an external site (a regex like /^https?:\/\// does the trick).

I would like to apply the target="_blank" attribute to these links. I was hoping to do this with angular when I am creating my links:

<ul>     <li ng-repeat="link in navigation">         <a ng-href="{{link.href}}" [add target="_blank" if link.href matches /^https?:\/\//]>{{link.title}}</a>     </li> </ul> 

Can anyone help me out?

Thanks

like image 953
Ben Guest Avatar asked May 10 '14 17:05

Ben Guest


People also ask

Can you add target _blank to URL?

You can use the target="_blank" attribute if you want your users to click on a link that opens up a new browser tab. The target="_blank" attribute is used inside the opening anchor tag like this.

Is Target _blank deprecated?

It looks like target="_blank" is still alright. It is listed as a browsing context keyword in the latest HTML5 draft.

Can you add target _blank in CSS?

Unfortunately, no. In 2013, there is no way to do it with pure CSS.

What should target _blank do when included in a link tag?

A target attribute with the value of “_blank” opens the linked document in a new window or tab. A target attribute with the value of “_self” opens the linked document in the same frame as it was clicked (this is the default and usually does not need to be specified).


2 Answers

I was just about to create a directive as suggested and then realised that all you actually need to do is this:

<a ng-attr-target="{{(condition) ? '_blank' : undefined}}">   ... </a> 

ng-attr-xyz lets you dynamically create @xyz, and if the value is undefined no attribute is created -- just what we want.

like image 159
Mark Birbeck Avatar answered Sep 28 '22 11:09

Mark Birbeck


Update

Or use a directive:

module.directive('myTarget', function () {     return {         restrict: 'A',         link: function(scope, element, attrs) {           var href = element.href;           if(true) {  // replace with your condition             element.attr("target", "_blank");           }         }     }; }); 

Usage:

<a href="http://www.google.com" my-target>Link</a> 

When you don't need to use this with Angular routing you can simply use this:

<a href="http://www.google.com" target="{{condition ? '_blank' : '_self'}}">Link</a> 
like image 28
Sebastian Avatar answered Sep 28 '22 11:09

Sebastian