Skip to content

Instantly share code, notes, and snippets.

@brianmfear
Created January 26, 2018 17:22
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save brianmfear/754e62a39a5f0f3ddde8fda290eb33d2 to your computer and use it in GitHub Desktop.
Save brianmfear/754e62a39a5f0f3ddde8fda290eb33d2 to your computer and use it in GitHub Desktop.
Lightning Add/Filter List
<aura:application extends="force:slds">
<!-- All items added to the list -->
<aura:attribute name="data" type="List" default="[]" />
<!-- The list of currently viewable items -->
<aura:attribute name="filteredData" type="List" default="[]" />
<!-- Input for a new item -->
<aura:attribute name="newItem" type="String" />
<!-- Input for the filter text -->
<aura:attribute name="filter" type="String" />
<!-- Real time filtering based on changes to the filter text -->
<aura:handler name="change" value="{!v.filter}" action="{!c.updateFilter}" />
<!-- Wrapper element to support Enter key -->
<div onkeyup="{!c.key}">
<!-- New string to add to the list -->
<lightning:input aura:id="newItemBox" name="x" value="{!v.newItem}" label="Add" />
</div>
<!-- Add to list -->
<lightning:button label="Add" onclick="{!c.add}" />
<!-- Filter input -->
<lightning:input name="x" value="{!v.filter}" label="Filter" />
<hr />
<!-- List of all items when filter = "", or case insensitive match otherwise -->
<aura:iteration items="{!v.filteredData}" var="row" indexVar="rowIndex">
<lightning:input disabled="{!true}" name="x" value="{!row}" label="{!'Item '+(rowIndex+1)}" />
</aura:iteration>
</aura:application>
({
// Detect Enter key
key: function(component, event, helper) {
if(event.which === 13) {
helper.add(component);
helper.updateFilter(component);
}
},
// Button click handler
add: function(component, event, helper) {
helper.add(component);
helper.updateFilter(component);
},
// Fired when the filter changes
updateFilter: function(component, event, helper) {
helper.updateFilter(component);
}
})
({
// Add a new item to the list
add: function(component) {
var data = component.get("v.data"),
newItem = component.get("v.newItem");
component.find("newItemBox").focus();
if(!newItem) {
return;
}
data.push(newItem);
component.set("v.newItem", null);
},
// Apply filter to the list of all items
updateFilter: function(component) {
var data = component.get("v.data"),
term = component.get("v.filter"),
newdata = data.filter(word => (!term) || word.toLowerCase().indexOf(term.toLowerCase()) > -1);
component.set("v.filteredData", newdata);
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment