有条件地添加target =" _blank"基于href的链接,即使插入href也是如此

时间:2014-11-17 14:23:56

标签: angularjs angularjs-directive

有一个类似的问题,但它只适用于硬编码的href,而不是由angular插值的href。见Conditionally add target="_blank" to links with Angular JS

我正在寻找的解决方案最好通过以下指令说明:

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

问题是该指令在angular完成任何插值之前运行,因此所有链接都是相对的。有干净的方法吗?我不能使用变异观察者,因为我必须支持IE9。

2 个答案:

答案 0 :(得分:2)

解决方案最终非常简单。 Angular提供了一种内置的方法来观察属性并对变化做出反应:

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';
      }
    }
  }
}

答案 1 :(得分:0)

我建议使用已提供的2选项:

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

并在指令控制器中设置条件变量,具体取决于位置。

如果您为此问题提供沙箱,那将非常有用。

UPD:如果你想要更多的黑客,你可以 $ timeout 并将其包装在那里。