[SalesForce] How to remove items from a dynamic list in Lightning component

There are use cases, such as the expense tracker app in the Lightning Components Developer's Guide, where users are entering data into a dynamic list that grows with each user input submission. My question is, in these situations, what is the most efficient way to implement a UI element that allows the user to remove an item from the list?

enter image description here

Best Answer

Luckily the aura:iteration component has a super convenient, built-in attribute called indexVar. By leveraging indexVar I am able to pass the array index to the controller action, which can then use Array.prototype.splice() to remove an element from the list.

For example, consider the following aura:iteration element:

<aura:iteration items="{!v.leads}" var="lead" indexVar="i">
    <tr>
        <td>
            <ui:button label="Remove" press="{!c.handleRemoveLeadButtonClick}">
                <span data-index="{!i}"></span>
            </ui:button>
            <a href="#" data-index="{!i}" onclick="{!c.handleRemoveLeadAnchorClick}">
                Remove
            </a>
        </td>
        <td>{!lead.FirstName}</td>
        <td>{!lead.LastName}</td>
        <td>{!lead.Company}</td>
        <td>{!lead.Email}</td>
    </tr>
</aura:iteration>

I've intentionally included a ui:button and a standard HTML a (anchor) to show how to get the index value in both cases. The controller actions are shown below.

({
    handleRemoveLeadButtonClick : function(component, event, helper) {
        var self = this;  // safe reference

        var domEvent = event.getParams().domEvent;
        var bodySpan = domEvent.target.nextSibling;
        var index = bodySpan.dataset.index;
        helper.removeLead(component, index);
    },
    handleRemoveLeadAnchorClick : function(component, event, helper) {
        var self = this;  // safe reference

        var index = event.target.dataset.index;
        helper.removeLead(component, index);
    }
)}

And helper.removeLead() is defined as follows:

({
    removeLead : function(component, index) {
        var leads = component.get("v.leads");
        leads.splice(index, 1);
        component.set("v.leads", leads);
    }
})