Search code examples
angularangularjs-ng-repeatangularjs-ng-click

How to loop based on button click using ng-repeat


The below code displays all the question and choices at a time but i want it to display 1 question and its particular options, after clicking next button it should display the next question.

<div ng-repeat="questionData in questionDatas">
    <h4 ng-bind="questionData.question"></h4>
    <div ng-repeat="choice in questionData.choices">
        <div class="choice"><input  ng-bind="choice" type="radio" ng-value="option" name="option"><label ng-bind="choice"></label></div>
    </div>
    <button ng-click="nextQuestion">Next</button>
</div>

Solution

  • You can achieve this by using ng-show

     <ul ng-repeat="item in questions track by $index"
              ng-show="(($index < (page * numRecords)) && ($index >= ((page - 1) * numRecords)))">
            <li>{{ item }}</li>
     </ul>
    

    DEMO

     var app = angular.module('app', []);
    
    app.controller('ctrlIndex', function($scope){
    
        
        $scope.numRecords = 1;
        $scope.page = 1;
    
        $scope.questions = []
        for (var i = 0; i < 10; ++i) {
            $scope.questions.push('question : ' + i);
        }
    
        $scope.next = function(){
            $scope.page = $scope.page + 1;
        };
    
        $scope.back = function(){
            $scope.page = $scope.page - 1;
        };
    });
    <!DOCTYPE html>
    <html>
    
      <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
        <link rel="stylesheet" href="style.css">
      </head>
    
      <body ng-app="app">
        <div ng-controller="ctrlIndex">
          <ul ng-repeat="item in questions track by $index"
              ng-show="(($index < (page * numRecords)) && ($index >= ((page - 1) * numRecords)))">
            <li>{{ item }}</li>
          </ul>
        
        <div><button ng-click="next()">Next </button></div>
        <div><button ng-click="back()">Prev</button></div>
        </div>
    </body>
    
    </html>