I am trying to increase a value on every button click in a lightning component. Is there a way to get a variable outside of individual function so I dont have to set the variable

function: (cmp, helper, event){
/////sample code 
 function2: (cmp, helper, event){
    var counter = 0;

function2 is being called by a click event on a lightning button, but since the "counter" variable is being set every time it will never increase on-click

  • 2
    you can create aura:attribute and set that variable
    – Himanshu
    Dec 26 '17 at 20:37
  • but every time I cmp.get() on a click event, that variable will be reset as well
    – MMeadows
    Dec 26 '17 at 20:41
  • 1
    add your code with aura:attribute and then we will rectify that
    – Himanshu
    Dec 26 '17 at 20:45
  • 1
    @Himanshu, I was not "cmp.set"-ing the value, just trying to console.log it. That was the problem so the solution was: set the attribute, cmp.get() in the controller, counter varible++, cmp.set(), then I could see it in the console. Thank you for your help
    – MMeadows
    Dec 26 '17 at 20:48

Your code should look like this.


<aura:component >
    <aura:attribute name="counter" default="0" type="integer"/>

    <lightning:button variant="brand" label="Submit" onclick="{!c.handleClick }" />

    Counter value is : {!v.counter}


    handleClick : function(component, event, helper) {



Now you can refer counter variable anywhere in your controller

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.