Search code examples
angularjsviewpartial

AngularJS: append partial instead of replacing current view


I wondered if it's possible to append a partial to the view, instead of replacing the previous one.

The usecase is as follows:

  • I'm building a questionaire
  • Upon starting the questionaire only 1 question is visible/in the DOM
  • The answer of question 1 dictates what question 2 should be
  • Upon answering question 1, question 2 gets appended to the DOM, under question 1
  • If question 1 is changed, all other questions are reset/removed from dom, and a fresh, unanswered question 2 appears (under 1)

Maybe using one partial a question is not the way to go, in that case please let me know what the preferred method would be (vanilla/no-angular JS?)


Solution

  • To give you a rough idea:

    Given your app is in angularjs, you should be having all your questions inside a model in a controller:

    $scope.questions = [
        {
            "question":"foo?",
            "options":["bar1","bar2","bar3","bar4"]
            "answer":2
        },
        {
    
        },
        {
    
        }
    ];
    
    // initially show the 1st question
    $scope.currentQuestIndex = 0;
    
    $scope.currentQuestion = $scope.questions[$scope.currentQuestIndex];
    

    And use the currentQuestion inside your view as:

    <div>Question: {{currentQuestion.question}}</div>
    

    When the user selects a correct answer, you could simply update the current question:

    $scope.submitAnswer = function(){
        // check if the answer is correct
        if(isCorrect){
            $scope.currentQuestion = $scope.questions[$scope.currentQuestIndex + 1];
        }
    }
    

    This would dynamically update your view! Thanks to the data-binding feature provided by angularjs.