Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open links in new window using AngularJS

Is there a way to tell AngularJS that I want links to be opened in new windows when the user clicks on them?

With jQuery I would do this:

jQuery("a.openInNewWindow").click( function() {     window.open(this.href);     return false; }) 

Is there an equivalent with AngularJS?

like image 661
KevSheedy Avatar asked Nov 20 '13 15:11

KevSheedy


People also ask

How to open url in new window using angularjs?

openNewTab = function (url) { $window. open(url, '_blank'); };

How can we open a link in new browser window?

To open a link in a new browser window, hold the Shift on then click the link or right-click the link and select Open link in New Window.

How to open new tab when clicking link in Angular?

To open the link in a new tab, we can use the <a> element by passing a target attribute with a value _blank .

How to open a new page on button click in Angular js?

Open the new pageA function named onButtonClick() is saved to the $scope. Inside the button, the $window. open() method is called. This will force the window to open the URL in a new window.


1 Answers

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");     }   }; }); 

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:

var app = angular.module('myApp', []);  app.controller('myCtrl', function($scope, $window) {   $scope.foo = function() {     $window.open('//facebook.com');   }; }); 

Live demo here (click).

Here are the docs for $window: http://docs.angularjs.org/api/ng.$window

You could just use window, but it is better to use dependency injection, passing in angular's $window for testing purposes.

like image 64
m59 Avatar answered Oct 16 '22 04:10

m59