Last active
November 15, 2019 08:58
-
-
Save idanen/284eb2b6c7efbaecb9b7 to your computer and use it in GitHub Desktop.
AngularJS directive to open external links in a new tab
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function () { | |
'use strict'; | |
angular | |
.module('externalLink', []) | |
.directive('a', AFactory); | |
function AFactory() { | |
return { | |
restrict: 'E', | |
link: function ($scope, $element, $attrs) { | |
$attrs.$observe('href', addTarget); | |
$attrs.$observe('ng-href', addTarget); | |
function addTarget(href) { | |
var domainPattern = /^(?:[a-z]{2,30}:)?(?:\/\/)([^:\/?]*)/i, | |
domainMatch = domainPattern.exec(href), | |
domain, currentDomain; | |
if (!domainMatch || domainMatch.length < 2) { | |
return; | |
} | |
domain = domainMatch[1].toLowerCase(); | |
currentDomain = window.location.hostname.toLowerCase(); | |
if (domain !== currentDomain) { | |
$attrs.$set('target', '_blank'); | |
// Mark that this directive added the target attribute | |
$element.data('externalLink', true); | |
} else if ($element.data('externalLink')) { | |
$attrs.$set('target', '_self'); | |
} | |
} | |
} | |
}; | |
} | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment