Skip to content Skip to sidebar Skip to footer

Ng-options In Angular For Arrays And Objects

First of all 2 working solutions: Example 1 - Array in Controller $scope.s1 = [ { 'name': 'Item1', 'id': 1 }, { 'name': 'Item2', 'id'

Solution 1:

I don't think that you can nest loops in ng-repeat, but, adding just a bit of business logic on your controller you can gain what you want!

hope it helps :)

(function(window, angular) {

  
  functionTestCtrl(vm, data) {
    var options = [];
    
    for(var group in data) {
      if(!data.hasOwnProperty(group)) { continue; }
      
      for(var i = 0, len = data[group].length; i < len; i++) {
        var item = data[group][i];
        
        item.group = group;
        
        options.push(item);
      }
    }
    
    vm.options = options;
    
    vm.current = options[0];
  }
  
  angular
    .module('test', [])
    .value('S2', {
      "myS2": [
        {
          "name"  : "Item1 mys2",
          "id"    : 1
        },
        {
          "name": "Item2 mys2",
          "id": 2
        }
      ],
      "myS3": [
        {
          "name"  : "Item1 mys3",
          "id"    : 1
        },
        {
          "name": "Item2 mys3",
          "id": 2
        }
      ]
    })
    .controller('TestCtrl', ['$scope', 'S2', TestCtrl])
  ;
})(window, window.angular);
<scriptsrc="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><sectionng-app="test"><articleng-controller="TestCtrl"><selectng-model="current"ng-options="item as item.name group by item.group for item in options"></select></article></section>

Post a Comment for "Ng-options In Angular For Arrays And Objects"