简体   繁体   中英

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?

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM