【问题标题】:How to statically or dynamically select an option in an select ngOption in angular如何静态或动态选择角度选择ngOption中的选项
【发布时间】:2014-03-12 22:00:24
【问题描述】:

我在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 设置几个选择选项。我希望能够通过更改模型来设置选择列表中的一个/两个选项,或者只需一个点击事件就足以让我继续前进。

【问题讨论】:

  • 请更正 Plunker URL...
  • Plunker 地址已更正。感谢您指出这一点。

标签: javascript angularjs select ng-options


【解决方案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>

【讨论】:

    猜你喜欢
    • 2020-02-21
    • 1970-01-01
    • 1970-01-01
    • 2014-12-23
    • 1970-01-01
    • 1970-01-01
    • 2016-01-05
    • 2015-11-04
    • 2011-05-25
    相关资源
    最近更新 更多