本文介绍了有条件地添加 target="_blank"与 Angular JS 的链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 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.

如果链接的 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).

我想对这些链接应用 target="_blank" 属性.我希望在创建链接时使用 angular 做到这一点:

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>

有人可以帮我吗?

谢谢

推荐答案

我正要按照建议创建一个指令,然后意识到您实际上需要做的就是:

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 允许您动态创建 @xyz,如果值为 undefined,则不会创建属性 - 只是什么我们想要.

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

这篇关于有条件地添加 target="_blank"与 Angular JS 的链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 05:57