Angular.js ngOptions to iterate over JSON objects

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/

Answers


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;
   }); 

Need Your Help

select jtable cells from particular column

java jtable

I have a JTable where I need to allow selection only from column2. If a user selects row1 x column3, then the selection should change to row1 x column2.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.