是否可以使用ngOptions来获取对象数组中的对象数组

时间:2016-07-08 02:28:29

标签: angularjs angularjs-ng-options

我有JSON结构:

$scope.menus = [
   {  
      "name":"about",
      "url":"/about",
      "submenus":[  
         {  
            "name":"company",
            "url":"/aboutcompany"
         },
         {  
            "name":"jobs",
            "url":"/jobs"
         }
      ]
   }
];

是否可以使用ngOptions访问子菜单

1 个答案:

答案 0 :(得分:0)

是的,您可以,首先应该在菜单对象内部进行迭代,然后您可以为每个子菜单数组进行选择,如下所示:



(function() {
  "use strict";
  angular.module('app', [])
    .controller('mainCtrl', function($scope) {
      $scope.selectedSubmenus = [];
      $scope.menus = [{
        "name": "home",
        "url": "/home",
        "submenus": [{
          "name": "employee",
          "url": "/aboutemployee"
        }, {
          "name": "something",
          "url": "/something"
        }]
      }, {
        "name": "about",
        "url": "/about",
        "submenus": [{
          "name": "company",
          "url": "/aboutcompany"
        }, {
          "name": "jobs",
          "url": "/jobs"
        }]
      }];
    });
})();

<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>

<body ng-controller="mainCtrl">
  <div ng-repeat="menu in menus track by $index">
    <strong>Menu name: </strong><span ng-bind="menu.name"></span>
    <select ng-options="submenu as submenu.name for submenu in menu.submenus" ng-model="selectedSubmenus[$index]">
      <option value="">Select something</option>
    </select>
    <hr>
  </div>
  Selecteds: <pre ng-bind="selectedSubmenus | json"></pre>
</body>

</html>
&#13;
&#13;
&#13;