Angular Select Dropdown,提供允许用户添加自定义选项的选项

时间:2015-10-30 21:06:26

标签: javascript html angularjs select

我在表单中有一个HTML Select Dropdown,要求用户从一些预先选定的安全问题中选择一个问题。 (例如“你最喜欢的城市是什么”,“你的车的颜色是什么”等等。)

如何在列表中添加另一个选项,例如“自己编写”,当用户选择它时,会显示一个新的输入框,供用户编写他/她自己的问题。

我能想到的一个策略是创建一个带有ng-show的输入元素,以根据Select的值隐藏/显示它。有没有更好的方法呢?

2 个答案:

答案 0 :(得分:2)

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.

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:

  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).

Hope this points you in the right direction.

Thanks,

Chris

答案 1 :(得分:1)

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.