【问题标题】:angular select show name and item角度选择显示名称和项目
【发布时间】:2016-03-18 06:35:10
【问题描述】:

我有以下项目,我想在select-tag 中显示:

    [var objects = {name:name1, items:2}, {name:name2, items:3}, {name:name3, items:0}]

我要创建的代码是:

    <select>
        <option value="name1">name1 [2]</option>
        <option value="name2">name2 [3]</option>
    </select>

简而言之,这将显示至少有一个 1 项的对象。我一直在尝试在AngularJS 中解决此问题,并且我有以下代码:

   <select ng-model="data.object" 
      ng-options="object.name as object.name [object.items] 
      when object.items > 0 for object in objects">
   </select>

【问题讨论】:

  • 有必要使用ng-options吗?
  • 不,不是,但我四处搜索,我猜这是最简单的选择。

标签: javascript html angularjs json ng-options


【解决方案1】:

我不确定您是否要隐藏或禁用包含 0 个项目的选项,因此这里有一些使用 ngOptions 和不使用 ngOptions 的示例。

var app = angular.module("app", []);

app.controller("controller", function($scope) {
  $scope.selectedOption = "";

  $scope.objects = [{
    name: "name1",
    items: 2
  }, {
    name: "name2",
    items: 3
  }, {
    name: "name3",
    items: 0
  }];
});
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.min.js"></script>
<div ng-app="app" ng-controller="controller">

  <pre>Selected option: {{selectedOption}}</pre>

  <h3>ngOptions w/ disabled</h3>
  <select ng-model="selectedOption" ng-options="object.name as (object.name + ' [' + object.items + ']') disable when (object.items == 0) for object in objects">
    <option value=""></option>
  </select>

  <h3>ngOptions w/ filtered array</h3>
  <select ng-model="selectedOption" ng-options="object.name as (object.name + ' [' + object.items + ']') for object in objects | filter:{items: '!0'}">
    <option value=""></option>
  </select>

  <h3>Options w/ ngRepeat and ngIf</h3>
  <select ng-model="selectedOption">
    <option value=""></option>
    <option ng-repeat="object in objects" value="{{object.name}}" ng-if="object.items > 0">
      {{object.name + ' [' + object.items + ']'}}
    </option>
  </select>

  <h3>Options w/ ngRepeat and ngDisabled</h3>
  <select ng-model="selectedOption">
    <option value=""></option>
    <option ng-repeat="object in objects" value="{{object.name}}" ng-disabled="object.items == 0">
      {{object.name + ' [' + object.items + ']'}}
    </option>
  </select>

</div>

【讨论】:

  • 哇太棒了,这是一个很好的解决方案!我用的是ng-repeatng-if
猜你喜欢
  • 1970-01-01
  • 2019-12-14
  • 2020-06-19
  • 2020-10-15
  • 2021-04-06
  • 2017-05-01
  • 2021-12-15
  • 2021-01-11
  • 2015-06-27
相关资源
最近更新 更多