使用 AngularJS 在新窗口中打开链接 [英] Open links in new window using AngularJS
问题描述
有没有办法告诉 AngularJS 我希望在用户点击链接时在新窗口中打开链接?
Is there a way to tell AngularJS that I want links to be opened in new windows when the user clicks on them?
使用 jQuery 我会这样做:
With jQuery I would do this:
jQuery("a.openInNewWindow").click( function() {
window.open(this.href);
return false;
})
有 AngularJS 的等价物吗?
Is there an equivalent with AngularJS?
推荐答案
这是一个指令,它将把 target="_blank"
添加到所有 标签中
href
属性.这意味着它们都将在新窗口中打开.请记住,指令在 Angular 中用于任何 dom 操作/行为.现场演示(点击).
Here's a directive that will add target="_blank"
to all <a>
tags with an href
attribute. That means they will all open in a new window. Remember that directives are used in Angular for any dom manipulation/behavior. Live demo (click).
app.directive('href', function() {
return {
compile: function(element) {
element.attr('target', '_blank');
}
};
});
同样的概念使侵入性更小(因此不会影响所有链接)并且更具适应性.您可以在父元素上使用它来影响所有子链接.现场演示(点击).
Here's the same concept made less invasive (so it won't affect all links) and more adaptable. You can use it on a parent element to have it affect all children links. Live demo (click).
app.directive('targetBlank', function() {
return {
compile: function(element) {
var elems = (element.prop("tagName") === 'A') ? element : element.find('a');
elems.attr("target", "_blank");
}
};
});
旧答案
似乎您只需在 <a>
标签上使用 "target="_blank"
.这里有两种方法:
Old Answer
It seems like you would just use "target="_blank"
on your <a>
tag. Here are two ways to go:
<a href="//facebook.com" target="_blank">Facebook</a>
<button ng-click="foo()">Facebook</button>
JavaScript:
JavaScript:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $window) {
$scope.foo = function() {
$window.open('//facebook.com');
};
});
以下是 $window
的文档:http://docs.angularjs.org/api/ng.$window
你可以只使用window
,但最好使用依赖注入,传入angular的$window
用于测试目的.
You could just use window
, but it is better to use dependency injection, passing in angular's $window
for testing purposes.
这篇关于使用 AngularJS 在新窗口中打开链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!