These are useful and common patterns for working with attribute
values in JavaScript.
Get an Attribute Value
component.get(String key) and
component.set(String key, Object value) retrieves and assigns
values associated with the specified key on the component. Keys are passed in as an expression,
which represents attribute values. To retrieve an attribute value of a component reference, use
component.find("cmpId").get("v.value"). Similarly, use
component.find("cmpId").set("v.value", myValue) to set
the attribute value of a component reference. This example shows how you can retrieve and set
attribute values on a component reference, represented by the button with an ID of
button1.
<aura:component>
<aura:attribute name="buttonLabel" type="String"/>
<lightning:button aura:id="button1" label="Button 1"/>
{!v.buttonLabel}
<lightning:button label="Get Label" onclick="{!c.getLabel}"/>
</aura:component>
This controller action retrieves the
label attribute
value of a button in a component and sets its value on the
buttonLabel
attribute.
({
getLabel : function(component, event, helper) {
var myLabel = component.find("button1").get("v.label");
component.set("v.buttonLabel", myLabel);
}
})
In the following examples, cmp is a reference to a
component in your JavaScript code.
To get the value of a component’s label
attribute:
var label = cmp.get("v.label");
Set an Attribute Value
To set the value of a component’s label
attribute:
cmp.set("v.label","This is a label");
Validate that an Attribute Value is Defined
To determine if a component’s label attribute is
defined:
var isDefined = !$A.util.isUndefined(cmp.get("v.label"));
Validate that an Attribute Value is Empty
To determine if a component’s label attribute is
empty:
var isEmpty = $A.util.isEmpty(cmp.get("v.label"));