0

I am trying to display a list of questions, one at a time, by the click of a button. After the first question loads it seems that javascript stops incrementing my counter variable that is stored as an attribute in the Lightning component. I tried just i++; like java, but that didn't work either.

({
   doInit : function(component, event, helper) {
    var questionlist = component.get("c.getQuestionList");
    questionlist.setCallback(this, function(response){
        var state = response.getState();

        if(state == "SUCCESS"){
            component.set("v.Questions",response.getReturnValue());
        } 

    });

    component.set("v.index",0);

    $A.enqueueAction(questionlist);
},

nextQuestion : function(component, event, helper) {
    var i = component.get("v.index");
    var questionList = component.get("v.Questions");
    i = ++i;
    component.set("v.currentQuestion", questionList[i]);
}
})

<aura:component implements="force:appHostable" controller="QuestionViewerController" >
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/> 
<aura:attribute name="title" type="String" required="true" default="Question Viewer"/>
<aura:attribute name="Questions" type="Question__c[]"/>
<aura:attribute name="currentQuestion" type="Question__c"/>
<aura:attribute name="index" type="Integer"/>

<lightning:card title="{!v.currentQuestion.Name}">
    <div>
        <p><lightning:formattedText title="{!v.currentQuestion.Name}" value="{!v.currentQuestion.body__c}"/></p>
        <lightning:buttongroup >
            <lightning:button iconName="standard:sales_path" onclick="{! c.nextQuestion }"/>
        </lightning:buttongroup>              
    </div>
</lightning:card>

  • 1
    you have to set the v.index to the incremented value in the nextQuestion method.. so that it retains the counter.. – Vamsi Krishna Dec 18 '17 at 0:28
2

In nextQuestion, pretend it was Java and was like this:

int i = reference.value;
i = new value;

In Java, that wouldn't change reference.value. Only setting reference.value = would change it. And that's what you need here.

In nextQuestion, after you increment i, do a component.set on v.index to change the component variable and not your local method variable.

Tip: Also, I find console.log statements very useful for debugging. You can console.log method variables or component.get variables and if you view the log in your browser that will help you troubleshoot in the general for cases like this.

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.