1

What's the best way for ng-options="" to iterate over JSON objects without ng-repeat=""... in order to retrieve all values.

  $scope.examples = 
  [
    {"name":"parent 1",
        "subs":  [
            {"name":"child a", "id":"1a"},  
            {"name":"child b", "id":"1b"}
        ]
    },
    {"name":"parent 2",
        "subs":  [
            {"name":"child a", "id":"2a"},  
            {"name":"child b", "id":"2b"}
        ]
    }
  ];

Should return, 1a, 1b, 2a, 2b for the <option> rendered in a single <select>

I mistakenly thought something like...

<select ng-model="data.sub" ng-options="item.id for item in examples.example.subs"></select>

...would iterate over sub objects. Do I need a separate function? Scope definition of some sort? Any help is appreciated.

http://jsfiddle.net/G9jGa/71/

4

1 回答 1

2

I think this is a very similar question:

   http://stackoverflow.com/questions/24860452/double-loop-to-get-ng-options

According to the answer, its not possible with the nested structure with ng-options. What you could do is flatten the data into an array instead.

I took the liberties of updating your jsfiddle as well. Please check it out:

    http://jsfiddle.net/G9jGa/72/

The following code is the code that I added to make it work:

    var app = angular.module('app', []);

    app.controller('Ctrl', function($scope) {
      $scope.examples = 
      [
       {"name":"parent 1",
        "subs":  [
          {"name":"child a", "id":"1a"},  
          {"name":"child b", "id":"1b"}
        ]
       },
       {"name":"parent 2",
        "subs":  [
           {"name":"child a", "id":"2a"},  
           {"name":"child b", "id":"2b"}
        ]
       }
    ];


   function flattenArray(array, fn)  {
      var output = [];
      for(var i = 0; i < array.length; ++i) {
         var result = fn(array[i]);
         if (result) 
            output = output.concat(result);
      }
      return output;
   }

   $scope.Groups = flattenArray($scope.examples, function(item) { 
        return item.subs;
   }); 
于 2014-09-26T17:44:57.213 回答