Michael
Michael

Reputation: 13616

How to append anchor element to div?

I work on my angularjs project.

I have this string in my controller:

"<a href="http://waze.to/?navigate=yes&ll=72.0274, 564.7814"  target="_blank">Open In Waze</a>"

And I have this div in my template:

 <div id="wazeArea" ng-init="editor.appandWazeLink(editor.siteId)"><i class="fa fa-car" aria-hidden="true"></div>

How can append anchor element above to div to make it clickable?

Upvotes: 1

Views: 806

Answers (3)

AB Udhay
AB Udhay

Reputation: 753

document.getElementById("wazeArea").appendChild(Anchor element in single quotes ' ');

You can use single quotes while making html string. It can allow double quotes inside that without need of escape characters

Upvotes: 0

Danmoreng
Danmoreng

Reputation: 2367

// 1. get the parent of the div
// 2. append the anchor to it
$("#wazeArea").parent().append($(string));
// 3. move the div inside of the anchor by appending it
$("#id_of_a").append($("wazeArea"));

Upvotes: 0

nixkuroi
nixkuroi

Reputation: 2269

This frustrated me a few times as well. You should be able to just embed the string name into it like this:

var htmlStringFromController = "<a href="http://waze.to/?navigate=yes&ll=72.0274, 564.7814"  target="_blank">Open In Waze</a>";  

And then call it from there.

<div id="wazeArea" ng-init="editor.appandWazeLink(editor.siteId)">{{htmlStringFromController}}</div>

The problem here is that angular doesn't want to inject raw HTML, right? So you can use $sce to accomplish that (AngularJS : Insert HTML into view)

But the question is, could you just inject the URL into an anchor tag that already exists in the div? Like this:

// controller code:
var URLFromController = "http://waze.to/?navigate=yes&ll=72.0274, 564.7814";

And then use this in the view, only displaying it if URLFromController is truthy.

<div id="wazeArea" ng-init="editor.appandWazeLink(editor.siteId)">
    <a ng-if="URLFromController" href="{{URLFromController}}" target="_blank">Open in Waze</a>
</div>

Upvotes: 1

Related Questions