简体   繁体   English

Angular选择带有选项的下拉菜单,以允许用户添加自定义选项

[英]Angular Select Dropdown with an option to let the user add a custom option

I have a HTML Select Dropdown in a form which asks the user to pick a question out of some pre-selected security questions. 我的表单中有一个HTML Select Dropdown,它要求用户从一些预先选择的安全性问题中选择一个问题。 (Such as "What's your favorite City", "What's the color of your car" etc.) (例如“您最喜欢的城市是什么”,“您的汽车是什么颜色”等)

How can I add another option to the list such as "Write your own" and when user selects it, a new Input box is shown for the user to write his/her own question. 如何将另一个选项添加到列表中,例如“写您自己的文本”,当用户选择它时,将显示一个新的“输入”框,供用户编写自己的问题。

One strategy I can think of is to create an input element with an ng-show to hide/show it based on the value of the Select. 我能想到的一种策略是创建一个带有ng-show的输入元素,以基于Select的值隐藏/显示它。 Is there a better way to do it? 有更好的方法吗?

There is a completely JS-free possibility found here: HTML combo box with option to type an entry which will likely require you to use the ng-options directive in the <select> tag. 在这里可以找到完全没有JS的可能性: HTML组合框,其中包含用于键入条目的选项,这可能会要求您在<select>标记中使用ng-options指令。

However, if you prefer to stick with your imported library(ies), you can start by injecting a text input box into your last option: 但是,如果您希望坚持使用导入的库,则可以从在最后一个选项中插入文本输入框开始:

  <select ng-model="selectedItem">
    <option ng-repeat="item in items" value="{{item}}">{{item}}</option>
    <option ng-blur="addItem()"><input type="text" placeholder="Write your own" id="newItem"></option>
  </select>

Then you define the ng-blur function to add the new item to the list of items in your array of items: 然后定义ng-blur函数,将新项目添加到项目数组中的项目列表中:

  addItem = function () {
      $scope.items[] = document.getElementById("newItem").value;
  }

Your variable names may vary, but this is the basic process I would use if I had the need. 您的变量名可能有所不同,但这是我需要的基本过程。 There may also be a better (Angular) directive or function that would work better for getting the value of your injected text box (possibly by name or parent-child relationships). 可能还有更好的(Angular)指令或函数,可以更好地获取注入的文本框的值(可能是通过名称或父子关系)。

Hope this points you in the right direction. 希望这能为您指明正确的方向。

Thanks, 谢谢,

Chris 克里斯

Your best bet is probably to write a custom directive that will simulate a select box (likely using styled radio buttons), but add an extra option in there that is an input. 最好的选择可能是编写一个自定义指令 ,该指令将模拟选择框(可能使用样式化的单选按钮),但在其中添加一个额外的选项作为输入。 I've done something similar for several projects and thought it isn't particularly difficult, but there is a lot to consider (including accessibility and keyboard controls). 我为几个项目做了类似的事情,并认为这并不是特别困难,但是要考虑很多事情(包括辅助功能和键盘控件)。

Or you can find one of the many open-source directives online. 或者,您可以在线找到许多开源指令之一。 While it might not be exactly what you're looking for UI-Select might be a good option. 尽管可能不是您要找的东西, UI-Select可能是一个不错的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM