有条件添加目标=" _blank"与角JS链接 [英] Conditionally add target="_blank" to links with Angular JS
问题描述
我建设角度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.
如果一个链接的href以http://或https://那么我假设的链接是一个外部网站(如正则表达式/ ^ HTTPS:\\ / \\ / /
的伎俩)。
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>
谁能帮我?
感谢
推荐答案
更新
或者使用指令:
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");
}
}
};
});
用法:
<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>
这篇关于有条件添加目标=&QUOT; _blank&QUOT;与角JS链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!