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/

1
  • How about making the "in" expression be a function call and in that function you'll need to create and return the flattened list of ids that you are looking for. Commented Sep 26, 2014 at 17:47

1 Answer 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;
   }); 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.