Tobi
Tobi

Reputation: 2040

Nested ng-repeat with array of objects which contain arrays

I can't get nested ng-repeat to work for a data-structure like the following:

options = [{name:"opt1", data:["a","b","c"]}, {name:"op2", data:["d","e","f"]}]

What I'm trying to accomplish is creating a select tag for each entry with options in it.

I thought that something like this should work:

<label ng-repeat="option in options">
  <div>{{option.name}}</div>
  <select>
    <option ng-repreat="val in option.data">{{val}}</option>
  </select>
</label>

but only the name is name is printed properly and only one option with no value in it is created.

Then I tried using track by $index in the inner ng-repeat:

<label ng-repeat="option in options">
  <div>{{option.name}}</div>
  <select>
    <option ng-repreat="val in option.data track by $index">
      {{option.data[$index]}}
    </option>
  </select>
</label>

but $index appears to be the outer $index and only counts from 0 to 1 with the given data.

What am I doing wrong?

Upvotes: 0

Views: 1026

Answers (1)

Vaibhav Raut
Vaibhav Raut

Reputation: 472

you should use ng-options instead of ng-repeat and with the help of ng-model you can get selected value. Here is a working code

angular.module("module", []).controller('mainCtr', ['$scope', function($scope){
    $scope.options = [{name:"opt1", data:["a","b","c"]}, {name:"op2", data:["d","e","f"]}];
}]);
<!DOCTYPE html>
<html ng-app="module">

    <head>
        <link rel="stylesheet" href="style.css" />
        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.7/angular.js">    </script>
        <script type="text/javascript" src="script.js"></script>
    </head>

    <body ng-controller="mainCtr">
        <div ng-repeat="option in options">
            <div>{{option.name}}</div>
            <select ng-model="opt" ng-options="opt for opt in option.data">
                <option value="">--- select ---</option>
            </select>
        </div>
    </body>
</html>

Upvotes: 3

Related Questions