Angular 中用于数组和对象的 Ng-Options

Ng-Options in Angular for Arrays and Objects

First of all 2 working solutions:

示例 1 - 控制器中的数组

$scope.s1 = [
    {
        "name": "Item1",
        "id": 1
    },
    {
        "name": "Item2",
        "id": 2
    }
];

查看 1

<select ng-model="select1" ng-options="foo.id as foo.name for foo in s1">
    <option value="">Select a Value</option>
</select>

示例 2 - 控制器中的对象

如果您知道 "myS2":

的名字,相同的概念也可能对您有所帮助
$scope.s2 = {

    "myS2": [
        {
            "name"  : "Item1",
            "id"    : 1
        },
        {
            "name": "Item2",
            "id": 2
        }
    ]
};

查看 2

 <select ng-model="select2" ng-options="foo.id as foo.name for foo in s2.myS2">
        <option value="">Select a Value</option>
 </select>

现在问题:

$scope.s2 有更多名称不同的对象 {myS1:[..] to mySn:[..]},我想将它们用作选项组名称?我如何在 ng-options 中做到这一点?

我不认为你可以在 ng-repeat 中嵌套循环,但是,在你的控制器上添加一点业务逻辑你可以获得你想要的!

希望对您有所帮助:)

(function(window, angular) {

  
  function TestCtrl(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);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<section ng-app="test">
  <article ng-controller="TestCtrl">
    
    <select ng-model="current" ng-options="item as item.name group by item.group for item in options">
    </select>
  </article>
</section>