Activity Forums Salesforce® Discussions How to pass the object being iterated to JS controller?

  • Abhinav

    Member
    June 9, 2016 at 7:48 pm

    Hi Himanshu,

    There is no need to create a child component:

    <aura:attribute name="stores" type="Account[]"/>
    <aura:iteration items="{!v.stores}" var="store" indexVar="idx">
    <div class="slds-card" data-record="{!idx}" onclick="{!c.goToStoreDetail}">
    <header class="slds-card__header slds-grid grid--flex-spread">
    <h2 class="slds-text-heading--medium slds-truncate">{!store.Name}</h2>
    </header>
    </div>
    </aura:iteration>

    As you can see, I have used indexVar attribute in the iteration. I then use the index values in the data attribute of Div. Now in the JS Controller you can use the following code to retrieve the record based on the index.

    var selectedItem = event.currentTarget; // Get the target object
    var index = selectedItem.dataset.record; // Get its value i.e. the index
    var selectedStore = component.get("v.stores")[index]; // Use it retrieve the store record

  • Hamayoun Khan

    Member
    September 9, 2019 at 4:20 pm

    I know this is old, but thank you very much Abhinav, this was causing me issues until I saw your (very elegant) solution.

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos