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
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.
It looks like target="_blank" is still alright. It is listed as a browsing context keyword in the latest HTML5 draft.
Unfortunately, no. In 2013, there is no way to do it with pure CSS.
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).
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With