Skip to main content
Hello, I'm new to Lightning Components and I decided to create a calculator using Lightning Components.

Given two numbers, when I click "Add" the result should be displayed.

Here's the code:

calculator.cmp

<aura:component >

    <aura:attribute name = 'num1' type = 'Integer' default = '15'></aura:attribute>

    <aura:attribute name = 'num2' type = 'Integer' default = '20'></aura:attribute>

    <aura:attribute name = 'sum' type = 'Integer'></aura:attribute>

    <div>

        <p>Add</p><lightning:button label = 'Add' onClick = '{!c.add}'/>

        <p>{!v.num1} + {!v.num2} = {!v.sum}</p>

    </div>

</aura:component>

calculatorController.js

({

    add : function(component, event, helper) {     

        //Add numbers

        var num1 = component.get('v.num1');

        var num2 = component.get('v.num2');

        var sumResult = num1 + num2;

        component.set('v.sum', sumResult);

        

    }

})

The add result doesn't show up when I click the button. It'd be great if someone helps! Thanks!
7 个回答
  1. 2019年7月15日 09:43
    Hi WonJeung,

    Change your onClick - > onclick.  In your case the controller method was not fire.

    Please try below code it works fine for me and let me know if this works for you. If still need modifications do let me know.

    Component :

    <aura:component >

        <aura:attribute name = 'num1' type = 'Integer' default = '15'></aura:attribute>

        <aura:attribute name = 'num2' type = 'Integer' default = '20'></aura:attribute>

        <aura:attribute name = 'sum' type = 'Integer'></aura:attribute>

        <div>

            <p>Add</p><lightning:button label = 'Add' onclick = '{!c.addMethod}'/>

            <p>{!v.num1} + {!v.num2} = {!v.sum}</p>

        </div>

    </aura:component>

    Controller :

     

    ({

        addMethod : function(component, event, helper) {     

            //Add numbers

            var num1 = component.get("v.num1");

            var num2 = component.get("v.num2");

            console.log(num1);

            console.log(num2);

            var sumResult = num1 + num2;

            component.set('v.sum', sumResult);

            

        }

    })

    I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

    Thanks,

    Ajay Dubedi
0/9000