Linking to external URL with different domain from

2019-06-19 02:20发布

All I am trying to do is include an anchor tag inside the html of a partial that links to an external site. Were this standard html, the code would simply be:

<a href="http://www.google.com" target="_blank">google</a>

As simple as this is, I cannot seem to find a working solution for getting past angular intercepting the route (or perhaps replacing my anchor with the https://docs.angularjs.org/api/ng/directive/a directive unintentionally?).

I have scoured SO and the rest of the web and seen a myriad of solutions for dealing with: links within the same domain, routing within the SPA, routing within a page (ala $anchorScroll) but none of these are my issue exactly.

I suspect it may having something to do with using $sce but I am an Angular n00b and not really sure how to properly use that service. I tried the following in my view controller:

$scope.trustUrl = function(url) {
    return $sce.trustAsResourceUrl(url);
}

with the corresponding:

<a ng-href="{{ trustUrl(item) }}">Click me!</a>

(as described here: Binding external URL in angularjs template)

but that did not seem to do the trick (I ended up with just href="{{" in the rendered page).

Using a plain vanilla anchor link like this:

<a href="http://www.google.com">google</a>

also failed to do the trick (even though some online advised that standard href would cause a complete page reload in angular: AngularJS - How can I do a redirect with a full page load?).

I also tried adding the target=_self" attribute but that seemed to have no effect either.

Do I need to write a custom directive as described here?

Conditionally add target="_blank" to links with Angular JS

This all seems way too complicated for such a simple action and I feel like I am missing something obvious in my n00bishness, at least I hope so because this process is feeling very onerous just to link to another url.

Thanks in advance for any solutions, advice, refs or direction.

1条回答
小情绪 Triste *
2楼-- · 2019-06-19 03:02

It turns out that I did in fact have all anchor links in the page bound to an event listener and being overridden. Since that code was fundamental to the way the page worked I did not want to mess with it. Instead I bypassed it by using ng-click to call the new url as follows:

HTML:

<a class="navLinkHcp" href="{{hcpurl}}" title="Habitat Conservation Plan" target="_blank" ng-click="linkModelFunc(hcpurl)">Habitat Conservation Plan</a>

Controller:

$scope.hcpurl = 'http://eahcp.org/index.php/about_eahcp/covered_species';

$scope.linkModelFunc = function (url){
  console.log('link model function');
  $window.open(url);
}

And voila! Good to go. Thanks again to KevinB for cluing me in that this was probably the issue.

查看更多
登录 后发表回答