Newer Version Available
Working with Attribute Values in JavaScript
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.
1<aura:component>
2 <aura:attribute name="buttonLabel" type="String"/>
3 <ui:button aura:id="button1" label="Button 1"/>
4 {!v.buttonLabel}
5 <ui:button label="Get Label" press="{!c.getLabel}"/>
6</aura:component>This controller action retrieves the label attribute
value of a button in a component and sets its value on the buttonLabel
attribute.
1({
2 getLabel : function(component, event, helper) {
3 var myLabel = component.find("button1").get("v.label");
4 component.set("v.buttonLabel", myLabel);
5 }
6})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:
1var label = cmp.get("v.label");Set an Attribute Value
To set the value of a component’s label attribute:
1cmp.set("v.label","This is a label");Validate that an Attribute Value is Defined
To determine if a component’s label attribute is defined:
1var 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:
1var isEmpty = $A.util.isEmpty(cmp.get("v.label"));