3

I am fairly new to the lightning component framework and I use aura:iteration to display a list of record and some information. Each item is contained in a div and I would like to retrieve the record from the list when its div is clicked.

What is the best way to do that?

Here's the code:

   <div onclick="{!c.clickEvent}">
        <p>{!index}</p>
        <p>{!inspection.Building__r.Name}"</p>
        <p>{!inspection.Name}</p>                               
        <p>{!inspection.Inspection_Type__c}</p>
        <p>{!inspection.Status__c}</p>  
   </div>

Thanks

1 Answer 1

4

The entire lightning component framework works on event driven pattern .So there will be a publisher and listener.

enter image description here

Lets assume i have list of Accounts using aura:iteration ,something like below

<div class="list-group" aura:id="listview">
    <aura:iteration items="{!v.lstAccnts}" var="account">
        <c:LightningSPAlist act="{!account}"/>
      </aura:iteration>
</div>

Observe how each list item is also a component .Hence LightningSPAlist item would be like below

<aura:component >
 <aura:attribute name="act" type="Account"/>
 <aura:registerEvent name="selectAccount" type="c:selectAccount" />
        <a href="#" aura:id="{!v.act.Id}" onclick="{!c.select}" class="list-group-item">
            <h4 class="list-group-item-heading">{!v.act.Name}</h4>
            <p class="list-group-item-text">Phone :{!v.act.Phone}</p>
        </a>
</aura:component>

The JS controller function once we select an Account

({
select : function(component, event, helper) {
    var account = component.get("v.act");
    var selectEvent = $A.get("e.c:selectAccount");
    selectEvent.setParams({ "saccount": account });
    selectEvent.fire();
   },
 })

Observe above how an event is fired off ,the event file defination is below

<aura:event type="APPLICATION">
  <aura:attribute name="saccount" type="Account"/>

The listener component will handle this event and perform actions based on captured event

<aura:handler event="c:selectAccount" action="{!c.populatedetail}"/>

The JS function

  ({
   populatedetail: function(component, event, helper) {
            var selected = event.getParam("saccount");
            component.set("v.actdetail",selected);
  },
 })
2
  • 1
    Thanks Mohit your solution worked like a charm thank you!
    – MaxPaq
    Commented Jan 15, 2016 at 19:56
  • 1
    Aura Id can be only constanct string. aura:id="{!v.act.Id}" will not work
    – Gloomcore
    Commented Feb 22, 2017 at 22:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .