简体   繁体   中英

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?

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>

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

// 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"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM