File download links with angulars UI-Router
Asked Answered
K

1

15

I'm trying to create a simple link in my angularJS app to files that have been uploaded. I have no problem producing the link, as this is pretty trivial. The issue I have however, is that the routing system I have intercepts the link and tries to load it within angular, which of course fails and just returns to the default route. This of course, is not really the behaviour that I want. My links are produced using

<a href="{{doc.url}}">{{doc.name}}</a>

I've also tried with

<a ng-href="{{doc.url}}">{{doc.name}}</a>

But obviously that doesn't change the resulting link. The resulting HTML is

<a class="ng-binding" href="/uploads/attachment/file/13/FILENAME.pdf">FILENAME.pdf</a>

Which is correct. Now though, the moment I click the link, I just get taken back to my default route. What can I do to stop ui-router trying to handle this link?

Karee answered 22/6, 2013 at 18:17 Comment(0)
U
31

Google gave me this:

"If you don't want AngularJS to "trap" links in anchors, add target="_self" .

<a href="..." target="_self">On Error GoTo Hell</a>

source: https://coderwall.com/p/em4vua

Btw, next time maybe don't tag this RoR, as it is purely an angularjs issue

Unbelievable answered 22/6, 2013 at 18:21 Comment(7)
Ah perfect thanks! Works a charm :) Yeah fair comment, just figured if it actually made a difference then people would know it's rails as I didn't explicitly mention itKaree
target="_blank" also worked well in my case. Thanks.Teran
is it a clean solution?Jester
target attribute didn't work for me, I don't know why really. What finally worked was adding the download attribute, like this: <a href="{{downLoadLink}}" target="_self" download="{{ selectedFile.original.name }}">{{ selectedFile.original.name }}</a>Despot
Tnx! Indeed, angular Modifies the default behavior of the html A tag.... I thought this was a webpack thing. Glad I ran into this post.Imbrue
I've just spent over a day trying to work out how to do this. I could get it working with a URL-encoded blob but not with a normal url of a file on the server. I was on the verge of uploading the file myself with fetch and creating a blob URL when I found this post. All I needed was the addition of target="_self"! Thank you!Salt
And yes I'm still using AngularJS in 2023. The project was written a while ago.Salt

© 2022 - 2024 — McMap. All rights reserved.