Victor Cui
Victor Cui

Reputation: 1705

Insert javascript variable inside href attribute

I'm trying to dynamically generate an HTML link and have that link be the href attribute of my anchor tag inside my AngularJS application. I have the code below:

const objectUrl = baseUrl + s3Bucket + '/' + objectKey;
const link = '<a href=`${objectUrl}`> MyLink</a>';

I thought that using JS's string templating would work but this inserts %60$%7BobjectUrl%7D%60 at the end of URL. I've also tried

const link = '<a href={{objectUrl}}> MyLink</a>';

but that gives me the same literal string %60$%7BobjectUrl%7D%60. Is there any way to insert the variable so that the href link becomes baseUrl + s3Bucket + '/' + objectKey?

Upvotes: 1

Views: 98

Answers (4)

Daan
Daan

Reputation: 2799

You have the template string the other way around. The ` should go on the outside of your string.

const objectUrl = 'yourURL';
const link = `<a href="${objectUrl}">MyLink</a>`;

console.log(link);

Upvotes: 1

yuval.bl
yuval.bl

Reputation: 5074

Use template literal like this:

const link = `<a href="${objectUrl}">MyLink</a>`

Upvotes: 0

Akash Srivastav
Akash Srivastav

Reputation: 766

Try

<a ng-attr-href="{{objectUrl}}">My Link</a>

Upvotes: 0

suresh bambhaniya
suresh bambhaniya

Reputation: 1687

try this

const link = '<a href="'+objectUrl+'" > MyLink</a>';

Upvotes: 2

Related Questions