0

我在http://www.bennadel.com/blog/2452-Mixing-Static-And-Dynamic-Data-In-An-AngularJS-Select-Menu.htm观看了一段视频,它几乎满足了我的需求。这个 Pluncker http://plnkr.co/edit/iy8mdpyg40ot8KEaOjz6?p=preview有一个例子,说明我如何使用 AngularJS 设置几个选择选项。我希望能够通过更改模型来设置选择列表中的一个/两个选项,或者只需一个单击事件就足以让我继续前进。

4

1 回答 1

1

虽然select元素历史上限制你options只有一个字符串值,但 ngOptions 指令允许你使用成熟的对象作为<option>值。

但是必须记住,ngOptions在将列表中的对象与预选模型中的对象进行比较时,将使用严格的比较。

这意味着,在预选模型时,您必须将其设置为与迭代列表中选定对象完全相同的实例:

PLUNKER

app.controller('MainController', function($scope) {

  $scope.options1 = [
    {id: 1, label: 'label1', type: 'type1', parentType: 'parentType1'},
    {id: 1, label: 'label2', type: 'type2', parentType: 'parentType1'},
    {id: 1, label: 'label3', type: 'type3', parentType: 'parentType2'},
    {id: 1, label: 'label4', type: 'type4', parentType: 'parentType2'},
    {id: 1, label: 'label5', type: 'type5', parentType: 'parentType3'}
  ];

  $scope.type = "";

  $scope.options2 = [
    {id: 1, label: 'specialLabel1', type: 'label1', parentType: 'parentType1'},
    {id: 1, label: 'specialLabel2', type: 'label1', parentType: 'parentType2'},
    {id: 1, label: 'specialLabel3', type: 'label2', parentType: 'parentType3'},
    {id: 1, label: 'specialLabel4', type: 'label2', parentType: 'parentType4'},
    {id: 1, label: 'specialLabel5', type: 'label3', parentType: 'parentType5'}
  ];

  $scope.get = function(myarray, type) {
    return myarray.filter( function(value, index, arr) { 
      return value.type == type.label 
    });
  }

  $scope.select = function () {
    $scope.type = $scope.options1[2];
  }

});
<body ng-app="myApp" ng-controller='MainController'>

  <select 
    ng-model="type" 
    ng-options="p as p.label group by p.parentType for p in options1"
  ></select>

  <select 
    data-ng-model="speciality" 
    ng-options="p as p.label group by p.type for p in get(options2, type)"
  >
    <option value="">None</option>
  </select>

    <hr />
    <button ng-click="select()">Set type</button>

</body>
于 2014-02-13T22:21:38.307 回答