2

I have a requirement to create label dynamically in a Lightning controller I tried the below code - But not working.

DivMethod : function(component, event,helper)
{
//Calling as per JS syntax
$("#div").append('<a  onclick = " HyperlinkMethod() " >Some text</a>');
//Calling as per Aura syntax --- this is working if it is defined in component. but not if created in controller
$("#div").append('<a  onclick =  "{!c.HyperlinkMethod }"  >Some text</a>');
},

HyperlinkMethod : function(component, event,helper) {
        alert("Hello");
    },
5

There are a few considerations to authoring robust and reusable components missing from above.

  • relying on DOM IDs (especially hard code ones) is a recipe for making a component that works until you have 2 or more in use in the same page. Instead leverage Lightning's so,union to this common issue and switch to aura:id instead using component.find("someAuraId").getElement()

  • inline JavaScript such as onclick="HyperlinkMethod()" violates Lightning's unsafe inline security policy and will be blocked at the browser level starting in Summer'16 as part of the upcoming security feature called Lightning LockerService. Inline JavaScript is a well known and often abused cross site scripting attack vector (opens up the potential for data being executed as code) that Lightning has been architected to protect against. The addEventListener() event wire up approach is correct and 100% compliant with security best practices

  • since the callback is going to execute outside of Lightning's natural event lifecycle you need to let it know that something happened so it can perform its automatic processing of any enqued action requests, rerendering, etc. You simply need to wrap the callback you pass to addEventListener() in a call to $A.getCallback()

With all of that said I'd like to back up an suggest that you do this in a Lightning Components way instead and model the label as a component and not even drop to the DOM level at all.

0

You can add a click event to the "a" element using plain javascript.

Try the following:

var divEl = document.getElementById("div");
var aEl = document.createElement("a");
aEl.text = "Some Text";
aEl.addEventListener("click", function(){alert("hello");}, false);
divEl.appendChild(aEl);

If you want to use components or helpers objects, you can try this:

var divEl = document.getElementById("div");
var aEl = document.createElement("a");
aEl.text = "Some Text";
var clickEvent = function(){
 if (component.isValid()){ //always check if component is valid
   alert("hello");
   //Do something with component object
 }
};
aEl.addEventListener("click", clickEvent, false);
divEl.appendChild(aEl);

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.