Search code examples
jsonangularjsng-options

Confused with AngularJS ng-options


I have this JSON (output extracted from Mozilla Firefox):

2015: Object
   02: Object
    monthname: "February"
   01: Object
    monthname: "January"

So, i want to use AngularJS directive: ngOptions.

I don't know how to access to these objects. I want to reproduce something like:

<select>
  <option value="2015-00">2015</option>
  <option value="2015-02">February</option>
  <option value="2015-01">January</option>
</select>

Solution

  • First step: Format your data into a single array/object that ng-options can work with. Multi-dimensonal data like you've got won't work.

    Assuming this is your source data:

    var data = {
        2015: {
            02: {monthname: 'February'},
            01: {monthname: 'January'}
        }
    };
    

    Format it into a flat object (key/value pairs):

    var options = {};
    for (var year in data) {
        if (!data.hasOwnProperty(year)) break;
        options[year+'-0'] = year;
        for (var month in data[year]) {
            if (!data[year].hasOwnProperty(month)) break;
            options[year+'-'+month] = data[year][month].monthname;
        }
    }
    

    That should result in options variable looking like this:

    {
        '2015-0': 2015,
        '2015-2': 'February',
        '2015-1': 'January'
    }
    

    Put these options into $scope so you can use them:

    $scope.options = options;
    

    Then use ng-options as follows:

    ng-options="key as value for (key,value) in options"
    

    Detailed information about ng-options formatting is available here.

    Jsfiddle example here.