0

I have an apex controller which returns a list to my javascript controller.
Within clinet side javascript, i want to iterate through list of the object and create one string which will contain anchor tags also. I used component.set("v.myString",customLongString) so that it can be viewed in lightning.

The javascript string is something like this :

An apple a day keeps the doctor away for <a href="javascript void(0); onClick="handleSomething();">#12344</a> times.

When the above string is rendered in lightning, it still displaying the HTML tags instead of making it as a hyperlink. Any idea what i can do for it ?. The string can contain multiple or 4 hyperlinks and many more text.

2

Whenever you are using

component.set("v.myString",customLongString);

it will literally print whats there in the variable customLongString. It will assume it to be a string and will not parse the string. Hence the HTML was displaying in the UI.

As a work around look at the below code

<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>

<!-- If your String is static. Try String Interpolation-->
<p>This is from static</p>
hello <a onclick="{!c.sayHello}" name="{!v.testList[1].strValue}">{!v.testList[1].strValue}</a> Chander

<!-- If your Stirng is dynamic - Build the list similar to the one in doInit method and loop through -->
<p>This is from dynamic</p>
<aura:iteration items="{!v.testList}" var="item">
    <aura:if isTrue="{!item.isOnclickEnabled}">             
        <a href="javascript:void(0)" onclick="{!c.sayHello}" name="{!item.strValue}">{!item.strValue}</a>&nbsp;
        <aura:set attribute="else">
            <span>{!item.strValue} &nbsp;</span>
        </aura:set>
    </aura:if>                  
</aura:iteration>    

In the controller build your dynamic testList and generate a string of your requirement. Onclick you will know which string you clicked and process it in the controller

({
    sayHello : function(cmp, event, helper) {
        var stringClicked = event.srcElement.name;
        alert(stringClicked);
    },

    doInit : function(cmp, event, helper){
        var testList = [
            {strValue : 'hello', isOnclickEnabled : false},
            {strValue : 'Mohan', isOnclickEnabled : true},
            {strValue : 'Chander', isOnclickEnabled : false}
        ];
        cmp.set("v.testList", testList);
    }
})

UI inth

| improve this answer | |
  • Got it. This is exactly what i am doing as an alternative – Darkdog Sep 4 '19 at 19:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.