There is a page

var myApp = angular.module('myApp', []); myApp.controller('MyCtrl', function ($scope) { var questions = new Array(2); questions[0] = { name: "Сколько будет 2 + 2 = ?", answers: [2, 3, 4, 5] }; questions[1] = { name: "Сколько будет 2 + 2 * 2 = ?", answers: [4, 6, 8] }; $scope.questions = questions; $scope.tab = 1; $scope.selectTab = function(setTab) { $scope.tab = setTab; } $scope.isSelected = function(checkTab) { return $scope.tab == checkTab; } }); 
 <!DOCTYPE html> <html> <head> <script data-require="angularjs@1.5.8" data-semver="1.5.8" src="https://opensource.keycdn.com/angularjs/1.5.8/angular.min.js"></script> <link rel="stylesheet" href="style.css" /> <script src="script.js"></script> </head> <body> <div ng-app='myApp' ng-controller="MyCtrl"> <h2> ВОПРОС </h2> <br> <div ng-show='isSelected(1)'> {{questions[0].name}}: <div class="radio-class"> <label ng-repeat="cur in questions[0].answers"> <input type="radio" name="radio"> {{cur}} <br> </label> </div> </div> <div ng-show='isSelected(2)'> {{questions[1].name}}: <div class="radio-class"> <label ng-repeat="cur in questions[1].answers"> <input type="radio" name="radio2"> {{cur}} <br> </label> </div> </div> <nav> <a href='#' ng-click='selectTab(1)'>1</a> <a href='#' ng-click='selectTab(2)'>2</a> </nav> </div> </body> 

Now there are only two div with questions. But in reality there will be more. Is it possible to somehow with the help of ng-repeat or in another way to avoid duplication of the div with the question?

When forming a block with a question, it is necessary to dynamically:

  • change attribute value ng-show='isSelected(n)' ;
  • change the index of the questions[n] collection;
  • and number the input element in its name="radioN" attribute.

    1 answer 1

    Try using $index :

     <body> <div ng-app='myApp' ng-controller="MyCtrl"> <h2>ВОПРОС</h2> <br> <div ng-repeat="question in questions" ng-show='isSelected($index+1)'> {{question.name}}: <div class="radio-class"> <label ng-repeat="cur in question.answers"> <input type="radio" name="radio" value="{{$index+1}}"> {{cur}} <br> </label> </div> </div> <nav> <a ng-repeat="question in questions" ng-click="selectTab($index+1)">{{$index+1}}</a> </nav> </div> </body>