kuanb
kuanb

Reputation: 1708

Nest ng-repeat in a <select> dropdown

I'd like to create a nested ng-repeat that allows me to include all questions in all chapters of a survey JSON in a dropdown <select> menu. What's the "right way" to do this? I could see creating an array just for this particular use case, but would rather not do that.

<select class="form-control" ng-model="chapter.jumpId">
    <span ng-repeat="chap in survey.chapters">
        <option ng-repeat="question in chap.questions" value="question.verbose">
            {{ question.id }}
        </option>
    </span>
</select>

Upvotes: 1

Views: 444

Answers (1)

Darshan Patel
Darshan Patel

Reputation: 2899

Html:

<select ng-repeat="chap in survey.chapters">
    <option ng-repeat="question in chap.questions" value="question.verbose">
        {{ question.id }}
    </option>
</select>

-----

<select>
    <option ng-repeat="sOption in sOptions" value="sOption.verbose">
        {{ sOption.id }}
    </option>
</select>

Js:

$scope.survey = {
        "chapters" : [
            {
                "questions" : [
                    {
                        "verbose" : "que1_verbose1",
                        "id": "que1_1"
                    },
                    {
                        "verbose" : "que1_verbose2",
                        "id": "que1_2"
                    }
                ]
            },
            {
                "questions" : [
                    {
                        "verbose" : "que2_verbose1",
                        "id": "que2_1"
                    },
                    {
                        "verbose" : "que2_verbose2",
                        "id": "que2_2"
                    }
                ]
            }
        ]
    };

$scope.sOptions = [];

angular.forEach($scope.survey.chapters, function(chapter) {
   angular.forEach(chapter.questions, function(question) {
      $scope.sOptions.push(question);
   });  
});

http://jsfiddle.net/9bc06fdv/27/

Upvotes: 2

Related Questions