Angularjs -删除选项从输入选择

angularjs - remove option from input select

本文关键字:输入 选择 选项 删除 Angularjs      更新时间:2023-09-26

我怎么也想不明白。使用AngularJS。

我有一个下拉选择字段与几个选项。它是表单的一部分,可以多次填写(即"添加另一个"类型的表单)。现在,其中一个选项可能只使用一次。如何在使用该选项后从所有其他选择字段中删除该选项?

我在做什么:

html

<select ng-model="item.itemtype">
    <option ng-repeat="i in itemtype" value="{{i}}" ng-init="item.itemtype = itemtype[0]">{{i}}</option>
</select>


angularjs

  $scope.Items = [
    { 'itemtype': '', 'desc': '', 'color': '' }
  ];
  $scope.itemtype = [
    'shirt',
    'pants',
    'hats',
    'shoes',
    'special'];


我试过的(真的不起作用)

  $scope.specialremove = function() {
    var exist = Items.indexOf("special")
    if (exist !== 0) {
      return '';
    }
    else {
      return 'special';
    }
  }

我希望我不需要转向任何其他框架来解决这个问题。如果我的代码中有任何问题/错误/效率低下,请随时指出。

首先可以使用ng-options:

ng-options="type for type in itemType"

最好有具有labelvalue属性的对象,以便将其写为

ng-options="type.value as type.label for type in itemType"

,并将显示的标签与所选内容的实际值分开。

在你的控制器中你应该有这样的内容:

  $scope.itemType= [
      ...
  ];
  $scope.selectedItem= $scope.itemType[0]; 

所以你可以这样写:

<select ng-Model="selectedItem" ng-options="item.value as item.label for item in itemType"></select>

要删除一个选定的项目,您可以watch控制器中的selectedItem的值:当它匹配您想要的值时,从数组中删除它并相应地更新selectedItem

这是一把基本小提琴。我只是在选中第三个选项后删除它,并将选中的项目重置为第一个。