I'm trying to build a super simple app where I have a list of Item and I can select them, and see the selected in a second list.
I have tried to setup a simple aura component:
<aura:component controller="MyApexControllerWithAuraEnabled">
<aura:attribute name="items" type="Item__c[]"/>
<aura:attribute name="itemsSelected" type="Item__c[]"/>
<aura:handler name="init" value="{!this}" action="{!c.doInit}" />
<div class="col-md-8">
<ul onchange="{!c.change}">
<aura:iteration items="{!v.items}" var="p">
<li class="item-li" onclick="{!c.select}">{!p.Name}</li>
</aura:iteration>
</ul>
</div>
<div class="col-md-4">
<ul onchange="{!c.change}">
<aura:iteration items="{!v.itemsSelected}" var="p">
<li class="item-li">{!p.Name}</li>
</aura:iteration>
</ul>
</div>
</aura:component>
In the controller, with doInit function I ask for Items__c object from Salesforce. When run the app, I see them, and it is good.
Now I want that, when a clik happen on a element, a new li element with same name appears also in the second list. But I don't manage to do it.
I have tried (inside the select function that is correctly called):
var action = component.get("v.items");
action.setCallback(this, function(response) {
console.log('**** ',response);
});
$A.enqueueAction(action);
But nothing is showed. I can retrive them from apex adding this code to my client controller:
var action = component.get("c.getItemByName");
action.setParams({
"name": event.target.innerHTML
});
action.setCallback(this, function(a) {
console.log('get back from server:', a.returnValue);
});
$A.enqueueAction(action);
But then I don't know how to add it to the itemSelected and I think it is a useless because I should already have that elements in the client.
Any advice please?
Best Answer
This example loads items on the client-side and captures the selected text value in the DOM. See the next example to capture the selected text value on the object itself.
Notice that I'm using a
ui:outputText
component instead of letting theli
element handle the click event. If you use this component, you can easily retrieve its value using theget("v.value")
syntax.When you click an
li
element, the second list updates with the name of the element you clicked. I'm not sure if this satisfies your use case but hope the example helps!Update: The following example uses an event to capture the selected item and its fields (including name etc).
Or grab the example at https://gist.github.com/dianawidjaja/8c644af14f2ea23d4f31.