Ng-Options in Angular for Arrays and Objects

落花浮王杯 提交于 2019-12-24 21:30:12

问题


First of all 2 working solutions:

Example 1 - Array in Controller

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

View 1

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

Example 2 - Object in Controller

The same concept may help you also here, if you know the name of "myS2":

$scope.s2 = {

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

View 2

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

Now the question:

$scope.s2 has further objects {myS1:[..] to mySn:[..]} with different names and I want'to use them as option group name? How can I do that in ng-options?


回答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) {

  
  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>


来源:https://stackoverflow.com/questions/34200484/ng-options-in-angular-for-arrays-and-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!