在 ui-select 中输入不在列表中的值

Entering in ui-select a value that is not in the list

In this plunk 我有一个 ui-select,其中包含一个包含名称的列表。我需要允许用户输入列表中的名称或不在列表中的名称。

如果我尝试输入不在列表中的名称,ui-select 会自动用列表中最接近的值替换该值。

有没有办法获取列表中没有的值?

HTML

      <ui-select ng-model="ctrl.person.selected" theme="bootstrap">
        <ui-select-match>{{$select.selected.name}}</ui-select-match>
        <ui-select-choices repeat="item in ctrl.people | filter: $select.search">
          <div ng-bind-html="item.name | highlight: $select.search"></div>
          <small ng-bind-html="item.email | highlight: $select.search"></small>
        </ui-select-choices>
      </ui-select>

您应该可以使用 tagging feature of ui-select to achieve what you want. Please see this Plunkr 进行演示 - 如果您在框中键入 "Gary" 然后跳出,它将填充 "Gary"。

要使用标记功能,您需要指定属性 taggingtagging-label,如下所示:

<ui-select ng-model="ctrl.person.selected" tagging="ctrl.tagTransform" tagging-label="false">

因为您的模型是一个对象数组(不是字符串),所以您需要指定一个函数来将 "new" 项添加到模型中:

vm.tagTransform = function(newTag) {
  var item = {
    name: newTag,
    email: newTag+'@email.com',
    age: 'unknown',
    country: 'unknown'
  };
  return item;
};

请注意,年龄和国家/地区已设置为 "unknown",因为我们无法仅通过输入姓名来确定它们是什么。电子邮件也默认为 "NAME@email.com"。

还有一个带有 ui-select 的 bug,其中 tagging-label 需要设置为 false(以便标记在单个 select模式)。不幸的是,这意味着您无法在键入时指定显示在下拉列表中的标记标签功能(尽管这在多个 select 模式下有效)。