有条件地添加target =" _blank"与Angular JS的链接

时间:2014-05-10 17:29:13

标签: javascript angularjs

我正在Angular JS中构建导航树。树中的大多数链接都指向我网站中的页面,但有些可能指向外部网站。

如果链接的href以http://或https://开头,那么我假设链接是针对外部网站的(像/^https?:\/\//这样的正则表达式就可以了。)

我想将target =“_ blank”属性应用于这些链接。当我创建链接时,我希望用角度来做这个:

<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>

任何人都可以帮助我吗?

由于

4 个答案:

答案 0 :(得分:66)

我正准备按照建议创建一个指令,然后意识到你真正需要做的就是:

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

ng-attr-xyz可让您动态创建@xyz,如果值为undefined,则不会创建任何属性 - 正是我们想要的。

答案 1 :(得分:33)

<强>更新

或使用指令:

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>

如果您不需要在Angular路由中使用此功能,则只需使用此功能:

<a href="http://www.google.com" target="{{condition ? '_blank' : '_self'}}">Link</a>

答案 2 :(得分:5)

建议的解决方案仅适用于硬编码的href。如果它们被插值则它们将失败,因为当指令运行时,angular不会进行任何插值。以下解决方案将适用于插值的href,并基于Javarome的解决方案:

yourModule.directive('a', function() {
  return {
    restrict: 'E',
    link: function(scope, elem, attrs) {
      attrs.$observe('href', function(){
        var a = elem[0];
        if (location.host.indexOf(a.hostname) !== 0)
          a.target = '_blank';
      }
    }
  }
}

答案 3 :(得分:2)

更简单的指令不需要通过处理所有<a href="someUrl">标记来更改HTML,如果someURL不针对当前主机,则添加target="_blank"

yourModule.directive('a', function() {
  return {
    restrict: 'E',
    link: function(scope, elem, attrs) {
      var a = elem[0];
      if (a.hostname != location.host)
         a.target = '_blank';
    }
  }
}